简体   繁体   English

在列表上使用addAll() <? extends E> a和b不起作用

[英]Using addAll() on List<? extends E> a and b doesn't work

Why doesn't this compile ? 为什么不编译

List<? extends Number> a = new ArrayList<>();
List<? extends Number> b = new ArrayList<>();
a.addAll(b);

Because it wouldn't be safe. 因为那不安全。

List<? extends Number> List<? extends Number> should be read as some list where the element type extends Number . List<? extends Number>应该被读为元素类型扩展Number一些列表 So in runtime a could be a List<Long> and b could be a List<BigInteger> . 因此,在运行时, a可以是List<Long>b可以是List<BigInteger> In that case, a.addAll(b) would mean "add all BigIntegers to the list of Longs" which, if allowed, obviously wouldn't be type safe. 在这种情况下, a.addAll(b)意味着“将所有BigIntegers添加到Longs列表中”,如果允许的话,显然不是安全的类型。

List<? extends Number> List<? extends Number> means List<? extends Number>表示

Items in this List have all the same class. 此列表中的项目具有相同的类别。 Not only do they extend Number, but are all the same type. 它们不仅扩展Number,而且都是同一类型。

Due to type erasure during compile, the byte code interpreter does not know (and cannot infer), whether the ? 由于编译期间的类型擦除,字节码解释器不知道(也无法推断),是否? of a and the ? 的和? refer to the same class. 指同一个班级。

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

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