new String[]{"s","s"} is of type String[] , not String . T[] not a subclass of T (unless T is an Object ).
Object[] is a subtype of Object , so the first one works. In fact, all types of arrays are a subtype of Object , including, perhaps surprisingly, arrays of primitives, for example int[] , although int not Object (*).
You can write the first 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"};
By the way, s2 demonstrates that arrays in Java are covariant. This is problematic as you can legally write:
s2[0] = new Object();
which will fail at runtime with an ArrayStoreException , since you cannot store Object references in String[] .
This is one reason why authors such as Josh Bloch give advice on “Preferred Lists for Arrays” (see Effective Java 2nd Ed Item 25), because Java collections such as List are not covariant and therefore do not suffer the same. problem.
(*) To add to the confusion, primitive arrays are not subtypes of Object[] , since primitives are not subtypes of Object . For example, it would be a compile-time error:
Object[] illegal = new int[5];
Andy turner
source share