我有問題與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