java - 正确使用java泛型?

标签 java generics iterator incompatibletypeerror

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

当我编译链接列表类时,我还收到了 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();

最佳答案

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
    }
}

关于java - 正确使用java泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16391480/

相关文章:

Javapoet 和泛型类声明

Java 7 但不是 Java 6 : "is not abstract and does not override abstract method"

c++ - 为 STL 迭代器重载运算符->

c++ - 如何实现构造函数,使其只接受使用 typeid 的输入迭代器?

java - Android Proguard - 运行时崩溃(未达到 "onCreate()")

java - Eclipse中的代码分析

java - 解析异构图

Java 泛型类标记

c++ - 迭代器运算符重载++ & -- 有一个参数 int 但未使用

java - java如何将int转boolean