Why can not I add an object of type Object into a

2020-02-14 20:19发布

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 ?

标签: java generics
5条回答
倾城 Initia
2楼-- · 2020-02-14 20:44
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.

If it were allowed:

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

查看更多
够拽才男人
3楼-- · 2020-02-14 20:47

Because Object is the most generic type in Java. It doesn't qualify to be called as specific to any level.

查看更多
贼婆χ
4楼-- · 2020-02-14 20:48

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>.

查看更多
Emotional °昔
5楼-- · 2020-02-14 20:50

"?" 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.

查看更多
姐就是有狂的资本
6楼-- · 2020-02-14 21:01

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());
查看更多
登录 后发表回答