Reputation: 71
I know following is true.
List<? extends Number> aNumberSuperList = new ArrayList<>();
List<? extends Integer> aIntegerSuperList = new ArrayList<>();
aNumberSuperList = aIntegerSuperList;
But what type of objects can be added to such a list.
List<? extends Number> aNumberSuperList2 = new ArrayList<>();
aNumberSuperList2.add(???)
Upvotes: 0
Views: 81
Reputation: 178363
Only null
can be added to a List<? extends Number>
. This is because the exact type parameter isn't known. A List<Integer>
could be assigned to this list, and so could a List<AtomicLong>
. The compiler must prevent a call to add
with anything but null
, to avoid the situation where a Integer
might be added to something that's referred to as a List<? extends Number>
, but is really a List<Double>
, for example. null
is the only safe thing to add here, because it can be of any type.
Upvotes: 7