Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array initialization with type casting

The following code makes me confused:

Object[] arr1 = new String[]{"a", "b", "c"};
Object[] arr2 = {"a", "b", "c"};

String[] a = (String[]) arr1; // ok
String[] b = (String[]) arr2; // ClassCastException

System.out.println(arr1.getClass().getName()); // [Ljava.lang.String;
System.out.println(arr2.getClass().getName()); // [Ljava.lang.Object;

I am trying to understand why the two initialization are different from each other. The first one is a post declaration, while the second one is a shortcut. The two are both declared as Object[]

My naive understanding is that:

Object[] arr2 = {"a", "b", "c"}; // is a syntax sugar of
Object[] arr2 = new Object[] {"a", "b", "c"};

So the runtime type of arr2 is exactly Object[] which can not be converted into String[].

But the things get strange here, because Java Array is covariant: String[] is a subclass of Object[] and arr2 is exactly a String[], casting back from Object[] to String[] on arr2 should work.

Any explanation on this is high appreciated.

like image 867
Hao Ren Avatar asked Jul 29 '15 12:07

Hao Ren


People also ask

How do you initiate an array in Java?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

Can you type cast arrays in Java?

You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

How do you initialize an array in Java with examples?

The number is known as an array index. We can also initialize arrays in Java, using the index number. For example, // declare an array int[] age = new int[5]; // initialize array age[0] = 12; age[1] = 4; age[2] = 5; ..

How do you declare an array and initialize it with 5 numbers in Java?

int a [] = new int[5]; [D]. Explanation: Option B is the legal way to declare and initialize an array with five elements.


1 Answers

Because arr2 is an Object[], there's nothing stopping you from writing

arr2[0] = new Object();

right before your cast, case in which the cast would no longer make sense anyway.

Because of the way initializer syntax works, also note the following:

Object x = {"a", "b"}; // error: illegal initializer for Object
Object[] a = {"a", "b"}; //a has class [Ljava.lang.Object; 
String[] b = {"a", "b"};  //b has class [Ljava.lang.String; 

The compiler determines whether you want your array to be an Object[] or a String[] based on your declaration.

like image 196
Vlad Avatar answered Oct 05 '22 04:10

Vlad