简体   繁体   English

在JAVA中解释这个泛型行为

[英]Explain this Generics Behavior in JAVA

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

The error I get is 我得到的错误是

"Type Mismatch : can't convert from MyList.Node to MyList.Node". “类型不匹配:无法从MyList.Node转换为MyList.Node”。

Not sure if this is related to the warning 不确定这是否与警告有关

"paramter Item is hiding the type item" “参数Item隐藏了类型项”

If I get a warning for private class ListIterator<Item> implements Iterator<Item> , why did I not get a warning for public class MyList<Item> implements Iterable<Item> ? 如果我收到private class ListIterator<Item> implements Iterator<Item>的警告,为什么我没有得到public class MyList<Item> implements Iterable<Item>的警告public class MyList<Item> implements Iterable<Item>

If the generic type parameter of the inner class ListIterator should be the same as the type parameter of the enclosing class MyList , you shouldn't declare it twice. 如果内部类ListIterator的泛型类型参数应与封闭类MyList的类型参数相同,则不应将其声明两次。

Change the inner class to: 将内部类更改为:

private class ListIterator implements Iterator<Item>

This way, the type of first and current will be the same. 这样, firstcurrent的类型将是相同的。

As Michael commented, you'll have to change the construction of the ListIterator instance to: 正如Michael评论的那样,您必须将ListIterator实例的构造更改为:

public Iterator<Item> iterator()  {
    return new ListIterator();
}

The warning very much is related. 警告非常相关。 Your generic type parameter in your inner class hides the generic type parameter in the outer class. 内部类中的泛型类型参数隐藏外部类中的泛型类型参数。 So Item in each scope is not the same, hence the two different Node<Item> s are actually different types. 因此每个范围中的Item不相同,因此两个不同的Node<Item>实际上是不同的类型。

See also: Troubleshooting "The type parameter T is hiding the type T" warning 另请参阅: 故障排除“类型参数T隐藏类型T”警告

Eran's answer shows how to fix it, so I won't repeat it. Eran的回答显示了如何解决它,所以我不会重复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM