好的,伙计们。这是修订版
class Node<E> { // (1)
private E data; // Data (2)
private Node<E> next; // Reference to next node (3)
Node(E data, Node<E> next) { // (4)
this.data = data;
this.next = next;
}
public void setData(E e) {} // (5)
public void xxxData(E e) {} // (6)
public E getData(E e) {return null;} // (7)
public static void main(String [] args) {
Node<? extends Integer> n1 = new Node<Integer>(1,null); //8
Node<? super Integer> n2 = new Node<Integer>(1,null); //9
n1.setData(new Integer(1)); //10 compiler error
n1.xxxData(new Integer(1)); //11 compiler error
n2.setData(new Integer(1)); //12 ok
}
}
这是一个重写,希望我能很好地表达我的困惑。
1. n1 是上限通配符。所以这不允许添加记录。第 10 条证明了这一点。
2. 第 11 条还证明,由于 xxxData 方法给出了相同的编译器错误,因此未使用方法名称(在本例中为“SET”以确定添加记录)。
3. n2 是下界通配符。由于方法名称在这里不起作用,编译器如何知道 setData 方法可以在 n2 上使用(因为 n2 是下限通配符,并且该通配符允许添加记录)?基本上,第 10 条和第 12 条中的 setData 方法有什么区别?
请记住,这些方法中没有任何反应。它为空或返回 null。
最佳答案
如果我正确理解了你的问题,我想这是因为 Integer 本身既是父类(super class)型又是子类型。
关于Java 泛型 : How does Java determine whether it's a set or get process for a bounded wildcard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7505663/