- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
考虑以下代码:
class Super {}
class Sub extends Super {}
class Test {
public static void main(String[] args) {
List<? extends Super> list = new ArrayList<Sub>(); //1
list.add(new Sub()); //2
}
}
第 1 行编译成功,但第 2 行编译失败:
The method add(capture#2-of ? extends Super) in the type List<capture#2-of ? extends Super> is not applicable for the arguments (Sub)
我的问题是:
1)为什么第一行编译成功?
2) 第 1 行是声明列表(或其他集合)的良好做法吗?
3) 为什么在第 1 行中将列表声明为 Sub 类型后,第 2 行编译失败?
4) Eclipse 的自动完成功能说现在列表中只允许“空”元素。为什么?
非常感谢!
最佳答案
1) Why does line 1 successfully compile?
第一行编译因为List<Sub>
是 List<? extends Super>
的子类只有当 List 不允许您向其中添加任何新成员时,情况才会如此。
?
意味着你不完全知道它是 List<Sub>
或 List<Sub1>
,因此允许将新元素添加到列表中是不安全的,因此它不允许这样做。
2) Is line 1 a good practice in declaring a List (or other collections)?
如果您已经知道它将是 List<Sub>
然后我发现没有任何用处,但是当您将 List 传递给其他类(如实用程序)时,通配符经常使用。
3) Why does line 2 fail compilation, after list was declared to be type Sub in line 1?
因为正如我已经解释过的,当您不知道确切的类型时,将任何元素添加到列表中是不安全的。
4) Eclipse's autocompletion says only "null" elements are allowed in list now. Why?
因为 null
是所有引用类型,这就是为什么您可以为任何对象分配一个值 null
.
永远记住PECS (Producer Extends Consumer Super) rule by Josh Bloch使用泛型时
好的引用资料:
关于java - 我可以在列表声明中使用泛型通配符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21574696/
我是一名优秀的程序员,十分优秀!