2012-01-30 81 views
1

嗨,我正在写一个链接列表数据类型。我有一个内部类节点,用于存储元素和后继。我目前遇到了我的节点中的getElement和列表中的get方法问题。 这是我在节点返回时泛型如何工作?

public E getElement(){ 
    return this.element; 
} 

其中元素是E元素声明的实例变量getElement。然而,当我尝试返回它我得到的方法是这样

public E get(int index){ 
    Node current; 
    if(index < 0 || index >= size) 
     throw new IndexOutOfBoundsException(); 
    if(index == 0) 
     return head.getElement(); 
    else{ 
     current = head; 
     for(int i = 0; i< index; i++){ 

     current = current.getSuccessor(); 
     } 
     return current.getElement(); 
    } 
    } 

我得到的错误不能从对象转换为E型我可以破解它周围,并键入其转换为一个E,但我觉得有关于泛型的一些潜在的东西,我失踪了。如果你猜这是为了做作业,你是对的,并且提前感谢你。

+2

我所看到的^ h omework问题比这个更糟糕。 – 2012-01-30 07:39:04

+0

getElement返回什么?一个东西? E型? – Adrian 2012-01-30 07:39:51

+0

可以请你发布全班和内班吗? – breezee 2012-01-30 07:40:10

回答

9

你可能想Node是通用,所以你不得不

public E get(int index){ 
    if(index < 0 || index >= size) 
    throw new IndexOutOfBoundsException(); 

    Node<E> current = head; 
    for(int i = 0; i < index; i++) { 
    current = current.getSuccessor(); 
    } 
    return current.getElement(); 
} 

(我已经简化你的代码一点点在同一时间,特别是在声明变量是一个好主意。在该点你确实需要他们

Node<E>应该是这样的:

class Node<E> { 
    private final E element; 
    private Node<E> successor; 

    public Node(E element) { 
     this.element = element; 
    } 

    // etc 
} 
+1

我不能赞同Jon Skeet的回答,因为我今天没有投票!诅咒! *再次挫败... * – blahman 2012-01-30 07:45:14

+1

让我为你做到这一点。 – 2012-01-30 07:46:20

+0

你是对的,我确实需要节点是通用的,非常感谢你的双向飞碟先生 – Erik 2012-01-30 08:00:50

3

假设Node类中通用的,像它应该是你的current变量应该这样声明:

Node<E> current; 

这同样适用于head,你可能有任何其他节点。