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
You are making a confusion between a List<Object>
and a List<?>
or List<? extends Object>
.
With a List<Object>
, you can put anything into it but List<?>
doesn't mean that this is a List or that it will (necessarily) receive a List<Object>
.
It could receive a List<Object>
, in this case adding an Object would be permissible; however, it could also receive anything else like a List<Integer>
, a List<String>
or a List<Animal>
. Obviously, you cannot add an Object to a List<Integer>
, a List<String>
or a List<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 a List<Object>
because the compiler won't remember that you have set it to a List<Object>
.
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
List<?> listObj = new ArrayList<String>();
listObj.add(new Object());
List<?> and `List<? extends Object>` are identical.
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.
List<?> listOfObjects = new ArrayList<Object>();
listOfObjects.add(new Object()); //not valid
somewhere in future
listOfObjects = new ArrayList<Animal>();
listOfObjects.add(new Animal());
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
"?" is called WildCard Capture which means type parameter matches an Unknown Type. This means
List<?> listObj = returnSomeList();
is a list of
Unknown Type
and you are trying to add an Object into a List of
Unknown Type.
The example posted by you will give you compile time error.
Because Object
is the most generic type in Java. It doesn't qualify to be called as specific to any level.