As far as I understand a List<?>
is definds as a list of some specific , yet unknown type . So whatever is the parameter type of this List
, it should be extending Object
because in Java you can not have any type that doesn't extend Object
. So why the following code doesn't get compiled ? How is it violating the the invariant of the listObj
List<?> listObj = returnSomeList();
listObj.add(new Object()); //Why does this not work ?
you cannot add any thing into the collection which uses ? extends Type syntax(wildcards with subtype).The reason is that you could just be adding the wrong type into the collection.
If it were allowed:
If it were allowed you just added an Animal into Object list, which voilates the whole reason of generic types. when you retrieve the Animal from the collection, you'd have to again do the instanceOf check to see if its the Animal and cast it back to animal as we did in pre-generics code.
Related Question
Because
Object
is the most generic type in Java. It doesn't qualify to be called as specific to any level.You are making a confusion between a
List<Object>
and aList<?>
orList<? extends Object>
.With a
List<Object>
, you can put anything into it butList<?>
doesn't mean that this is a List or that it will (necessarily) receive aList<Object>
.It could receive a
List<Object>
, in this case adding an Object would be permissible; however, it could also receive anything else like aList<Integer>
, aList<String>
or aList<Animal>
. Obviously, you cannot add an Object to aList<Integer>
, aList<String>
or aList<Animal>
.As the compiler doesn't remember the type of the object between instructions, adding an Object will always be illegal even if you set the
List<?>
to aList<Object>
because the compiler won't remember that you have set it to aList<Object>
."?" is called WildCard Capture which means type parameter matches an Unknown Type. This means
is a list of
and you are trying to add an Object into a List of
The example posted by you will give you compile time error.
List<?> listObj
can point to any type of List that can store different kind of objects.How do you think, would it be safe to let it add any objects if for example