解释JAVA中的泛型行为

3
public class MyList<Item> implements Iterable<Item> {
    Node<Item> first;
    int n = 0;

    private static class Node<Item>
    {
        private Item item;
        private Node<Item> next;
    }
    public Iterator<Item> iterator()  {
        return new ListIterator<Item>();
    }

    private class ListIterator<Item> implements Iterator<Item>  // parameter Item is hiding the type Item
    {
        private Node<Item> current = first;  // This does not compile

        public boolean hasNext() {
            return (current != null);   
        }

        public Item next() {
            Item item = current.item;
            current = current.next;
            return current.item;
        }       
    }
    ...
}

我收到的错误是
"类型不匹配: 无法从MyList.Node转换为MyList.Node"
我不确定这是否与警告有关
"参数Item隐藏了类型item"
如果我为private class ListIterator<Item> implements Iterator<Item>获得警告,那么为什么没有为public class MyList<Item> implements Iterable<Item>获得警告?
2个回答

5
如果内部类的泛型类型参数应该与外围类的类型参数相同,那么就不需要声明两次。
将内部类更改为:
private class ListIterator implements Iterator<Item>

这样,firstcurrent 的类型将是相同的。 正如 Michael 所评论的,您需要更改 ListIterator 实例的构建方式为:
public Iterator<Item> iterator()  {
    return new ListIterator();
}

1
@Michael 没有注意到。谢谢。 - Eran

3
警告信息与此密切相关。你内部类中的泛型类型参数掩盖了外部类的泛型类型参数。因此,每个作用域中的都不同,因此两个不同的Node实际上是不同的类型。
参见:Troubleshooting "The type parameter T is hiding the type T" warning Eran的答案展示了如何解决这个问题,所以我就不再赘述了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接