why can't cast Object[] to String[]

arrays, casting, java

Solution

Here's two reasons I can think of.

Firstly, if you change the original array, the casted array can become invalid. e.g.

 Object[] a = {"12","34","56"};   
 String[] b = (String[]) a; // pretend this is legal. a and b now point to the same array

 a[0] = new Object(); // clearly ok
 String x = b[0]; // No longer a string! Bad things will happen!

Secondly, the example you have chosen is very simple, but if you have a very large `Object[]` array and it's not clear to the compiler what is filling it, then it has no way of validating that every element of the array satisfies the cast.

Object[] a = new Object[10000];
// lots of weird and whacky code to fill the array with strings

String[] b= (String[]) a; // valid or no? The best-defined answer is to say no.

Problem

No error ``` Object[] a = new String[]{"12","34","56"}; String[] b = (String[]) a; ``` No error ``` Object a = new String[]{"12","34","56"}; String[] b = (String[]) a; ``` Run time error : ClassCastException ``` Object[] a = new Object[3]; a[0] = "12"; a[1] = "34"; a[2] = "56"; String[] b = (String[]) a; ``` Run time error : ClassCastException ``` Object[] a = {"12","34","56"}; String[] b = (String[]) a; ``` Of course, we can downcast an `Object[]` variable back to `String[]` if it was created as an `String[]`. My question is why we can not cast `Object[]` to `String[]` when it was created as `Object[]` but all its members are String? Is it because of security reason or just not that useful to implement this?

Original source

Related problems