Using java generics correctly?

Im having problems with java generics. When i use next() from the iterator it doesn’t return an object of the same type i instantiated it with. So i recieve an incompatible types error. Can anyone help?

I also recieve an Xlint warning when i compile the linked list class.

public class LinkedList
{

private Node sentinel = new Node();
private Node current;
private int modCount;

public LinkedList()
{
    // initialise instance variables
    sentinel.setNext(sentinel);
    sentinel.setPrev(sentinel);
    modCount = 0;
}
public void prepend(Type newData)
{
   Node newN = new Node(newData);
   Node 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 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());
    }
 }

}

Here is where the error occurs in the main class after the list is created and filled with different types of shapes.

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


Iterator
is a generic interface

, but your ListIterator
is neither generic nor parameterizes Iterator
. Start by making ListIterator
implement Iterator
:

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

or making ListIterator
generic as well (more complicated):

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

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

    public T next()
    {
        // snip
    }
}
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Using java generics correctly&quest;

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录