If an array of Object is an Object, why is an array of String not a String

后端 未结 6 1388
心在旅途
心在旅途 2021-02-15 12:06

Object class is super class to every class in Java. So every class should inherent the properties or behavior of Object class.

Then we can declare array of objects as sh

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-15 12:51

    new String[]{"s","s"} is of type String[], not String. T[] is not a subclass of T (unless T happens to be Object).

    Object[] is a subtype of Object, which is why the first one works. In fact, all array types are subtype of Object, including, perhaps surprisingly, arrays of primitives, like int[], even though int is not an Object (*).

    You could write the first one using more specific types:

    Object[] c = new Object[] {1,2,"22" };
    

    You can write the second as any of the following:

    String[] s1 = new String[]{"s","s"};
    Object[] s2 = new String[]{"s","s"};
    Object s3 = new String[]{"s","s"};
    

    Incidentally, s2 demonstrates that arrays in Java are covariant. This is problematic, since you can legally write:

    s2[0] = new Object();
    

    which would fail at runtime with an ArrayStoreException, since you can't store Object references in a String[].

    This is one of the reasons why authors like Josh Bloch give the advice "Prefer lists to arrays" (see Effective Java 2nd Ed Item 25), since Java collections like List are not covariant, and so don't suffer the same issue.


    (*) Just to add to the confusion, primitive arrays are not subtypes of Object[], as primitives are not subtypes of Object. For example, it would be a compile-time error to write:

    Object[] illegal = new int[5];
    

提交回复
热议问题