我有问题与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();
你确定你不是使用原始类型(例如的普通'LinkedList'而不是LinkedList的'')在你的代码的任何地方?这将是你所描述内容的可能解释。请显示你正在调用'next'的代码,哪里出错。 –
2013-05-06 03:13:58
'私人节点当前;'应该'私人节点当前;'? –
2013-05-06 03:18:35