我正在尝试这个 -
List<? extends Integer> l = new ArrayList<Integer>();
l.add(10);
编译器说 -
The method add(int, capture#1-of ? extends Integer) in the type List<capture#1-of ? extends Integer> is not applicable for the arguments (int)
为什么我无法将整数添加到整数列表,如果我无法添加整数,为什么编译器不会在第一行本身提示?
最佳答案
List<? extends Integer>
表示扩展 Integer
的一些未知类型的列表.暂时忘记Integer
是final
,在运行时它可能是一些子类型的列表 MyImaginaryInteger
,在这种情况下您不能添加 Integer
10 因为那样会破坏类型安全。这就是编译器不允许您添加元素的原因。
另一方面,List<? super Integer>
表示一些未知类型的列表,它是 Integer
的父类.在这种情况下,添加 Integer
值 10 是可以的,因为无论运行时该类型是什么,Integer
是它的一个子类型。
在您的特定情况下,使用此通配符根本没有意义——只需将其声明为 List<Integer>
.
关于java - 在泛型中使用 extends 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32924913/