简体   繁体   中英

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 . So in runtime a could be a List<Long> and b could be a 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.

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Iterables.html

What really worked for me was Guava:

com.google.common.collect.Iterables.concat(...)

List<? extends Number> List<? extends Number> means

Items in this List have all the same class. Not only do they extend Number, but are all the same type.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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