user67339
user67339

Reputation: 71

Java generics list

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

Answers (1)

rgettman
rgettman

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

Related Questions