Java generics - ArrayList initialization

后端 未结 6 1656
南方客
南方客 2020-12-02 13:58

It is known that arraylist init. should be like this

ArrayList a = new ArrayList();
ArrayList a = new ArrayList

        
6条回答
  •  没有蜡笔的小新
    2020-12-02 14:34

    ArrayList a = new ArrayList(); 
    

    Does not work because the fact that Number is a super class of Integer does not mean that List is a super class of List. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.

    ArrayList a1 = new ArrayList();
    a1.add(3);
    
    
    

    I cannot explain why it does not work. It is really strange but it is a fact. Really syntax is mostly used for return values of methods. Even in this example Object o = a1.get(0) is valid.

    ArrayList a = new ArrayList()
    

    This does not work because you cannot instantiate list of unknown type...

    提交回复
    热议问题