Common Ancestor to Java Array and List

后端 未结 6 1955
闹比i
闹比i 2020-12-18 19:54

In .NET, both array and list have Enumerable as ancestor, so a method that accept Enumerable as an argument can receive both array and list as its argument. I wonder if ther

6条回答
  •  遥遥无期
    2020-12-18 20:01

    Basically, arrays have an implicit type that is a subclass of object. See Arrays in the JLS:

       public static void main(String[] args) {
                int[] ia = new int[3];
                System.out.println(ia.getClass());
                System.out.println(ia.getClass().getSuperclass());
       }
    
       > class [I
       > class java.lang.Object
    

    The way arrays and lists are handled is also not the same when we consider covariance/contravariance.

    List l = new ArrayList(); // complain 
    Object[] l2 = new String[1]; // ok
    
    l2[0] = 4; // throw ArrayStoreException.
    
    
    

    It gets even worse if we consider generics, but that's another topic. All in all, I don't know the rationale of this design, but we need to live with it.

    提交回复
    热议问题