Java generics - ArrayList initialization

后端 未结 6 1645
南方客
南方客 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:22

    You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

    ArrayList is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList.

    That is, you can put an ArrayList into a variable declared with ArrayList. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList, to which no Integer can be added.

    Clearly, an ArrayList is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

    It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

    ArrayList> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList only contains but is not a wildcard type, the above rule does not apply.

提交回复
热议问题