List<?>
is quite different. If we try and add objects into a List<?>
, even if the object is of type Object
, we can't do it. It says,
add(capture<?>)
in java.util.List
cannot be applied to (java.lang.Object)
Now that might seem a bit restrictive. If you can't have any values being passed as parameters, which is what I mean when I say put into a list, then, what can you do with it?
Well, let's see why that restriction exists. To begin with, we know that arrays are covariant. So what that means is we could take an array of Strings and put that into an Object Array.
So here, if we take that first object and we assign it to a random String, everything will be fine. And if we assign it to a new Object, if we add that in, then we will get an ArrayStoreException
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Object
because of the unsafety of covariant arrays.
Well, in the case of List<?>
, what the Java compiler is trying to do for us by banning us from adding values into a List<?>
or a List<? extends Object>
is put us into a position where this type can only be safely used. And in fact, the only value that you are allowed to put into a List<?>
is the null
value because null
can be coerced into any type.