Java – generics – cannot be added to a list with unbounded wildcards
I instantiate the following list:
// I am just revising generics again and the following is just cursory code! List<? super Integer> someList = new ArrayList<Object>(); someList.add(new Object());
The above does not work I received a compiler error However, the following work should be done:
List<? super Integer> someList = new ArrayList<Object>(); someList.add(11);
I know you can add objects to a collection containing unbounded wildcards instead of bounded wildcards
But why doesn't that work? Object is a supertype of integer. Why can't I add it?
Solution
This declares that it is a list of super - typed things, not that the list can contain any super - typed integer In other words, for the compiler, it can be list < integer >, list < number > Or list < Object >, but it doesn't know which, so you can't add anything to the list The only thing you can safely add is integer, because it is guaranteed to be a subtype of any type that list may have
let me put it another way,? Represents a type, not any type This is a non - obvious but important difference