Why can not I add an object of type Object into a List<?>?

后端 未结 5 1452
忘了有多久
忘了有多久 2020-12-21 12:03

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

相关标签:
5条回答
  • 2020-12-21 12:34

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

    0 讨论(0)
  • 2020-12-21 12:43

    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());
    
    0 讨论(0)
  • 2020-12-21 12:46
    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

    0 讨论(0)
  • 2020-12-21 12:57

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

    0 讨论(0)
  • 2020-12-21 12:59

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

    0 讨论(0)
提交回复
热议问题