2013-05-06 74 views
0

我有问题与Java泛型。 当我从迭代器使用next()时,它不会返回我实例化的同一类型的对象。所以我收到一个不兼容的类型错误。 任何人都可以帮忙吗?正确使用java泛型?

我编译链接列表类时也收到Xlint警告。

public class LinkedList<Type> 
{ 

private Node<Type> sentinel = new Node<Type>(); 
private Node<Type> current; 
private int modCount; 

public LinkedList() 
{ 
    // initialise instance variables 
    sentinel.setNext(sentinel); 
    sentinel.setPrev(sentinel); 
    modCount = 0; 
} 
public void prepend(Type newData) 
{ 
    Node<Type> newN = new Node<Type>(newData); 
    Node<Type> temp; 
    temp = sentinel.getPrev(); 
    sentinel.setPrev(newN); 
    temp.setNext(newN); 
    newN.setPrev(temp); 
    newN.setNext(sentinel);   
    modCount++; 
} 


private class ListIterator implements Iterator 
{ 
    private int curPos, expectedCount; 
    private Node<Type> itNode; 
    private ListIterator() 
    { 
     curPos =0; 
     expectedCount = modCount; 
     itNode = sentinel; 
    } 

    public boolean hasNext() 
    { 
     return (curPos < expectedCount); 
    } 

    public Type next() 
    { 
     if (modCount != expectedCount) 
      throw new ConcurrentModificationException("Cannot mutate in context of iterator"); 
     if (!hasNext()) 
      throw new NoSuchElementException("There are no more elements"); 
     itNode = itNode.getNext(); 
     curPos++; 
     current = itNode; 
     return (itNode.getData()); 
    } 
} 

} 

这里是在创建列表并填充不同类型的形状后,主类中发生错误的位置。

shape test; 
Iterator iter = unsorted.iterator(); 
test = iter.next(); 
+0

你确定你不是使用原始类型(例如的普通'LinkedList'而不是LinkedList的'')在你的代码的任何地方?这将是你所描述内容的可能解释。请显示你正在调用'next'的代码,哪里出错。 – 2013-05-06 03:13:58

+0

'私人节点当前;'应该'私人节点当前;'? – 2013-05-06 03:18:35

回答

2

Iterator is a generic interface,但你的ListIterator既不是通用的,也不参数化Iterator。通过使ListIterator实现Iterator<Type>开始:

private class ListIterator implements Iterator<Type> { 
    // the rest should be fine 
} 

或进行ListIterator通用以及(更复杂):

private class ListIterator<T> implements Iterator<T> 
{ 
    private int curPos, expectedCount; 
    private Node<T> itNode; 
    private ListIterator() 
    { 
     curPos = 0; 
     expectedCount = modCount; 
     itNode = sentinel; 
    } 

    public boolean hasNext() 
    { 
     return (curPos < expectedCount); 
    } 

    public T next() 
    { 
     // snip 
    } 
} 
+0

更改迭代器后,我仍然遇到同样的问题。 – user2353235 2013-05-06 03:38:01

+0

除了不执行'remove()'的迭代器,基本代码编译对我来说很好。 http://ideone.com/OTYxvP – 2013-05-06 03:43:12

+0

如果他做了后者,他也应该让'ListIterator'不是内部类 – newacct 2013-05-06 06:57:53

0

你能张贴代码,告诉你如何使用它?

确保当您使用ListIterator类,你LinkedList<Something>.ListIterator泛型化了。否则,类型为LinkedList.ListIterator的迭代器将是原始类型,其next()将返回Object

也不要参数ListIterator。否则,它会影响外部类的类型变量。内部(非静态)类可以使用外部类的类型变量。此外,如果你这样做,你将不得不做LinkedList<Something>.ListIterator<Something>使其一致;你甚至不能执行LinkedList.ListIterator<Something>,因为你不能给一个原始类型的内部类赋予泛型参数。

+0

啊Thakyou两个家伙!它需要是 **迭代器ITER = unsorted.iterator(); **的 代替 **迭代器ITER = unsorted.iterator(); ** – user2353235 2013-05-06 03:56:36