Java – why can’t object [] be converted to string []

>No error

Object[] a = new String[]{"12","34","56"};
String[] b = (String[]) a;

>No error

Object a = new String[]{"12","56"};    
String[] b = (String[]) a;

>Runtime error: ClassCastException

Object[] a = new Object[3];
a[0] = "12";
a[1] = "34";
a[2] = "56";
String[] b = (String[]) a;

>Runtime error: ClassCastException

Object[] a = {"12","56"};    
String[] b = (String[]) a;

Of course, if an object [] variable is created as a string [], we can convert it back to string []

My question is why we can't convert object [] to string [] when object [] is created as object [] but all its members are strings. Is it for security reasons or is it not helpful to realize this?

Solution

Here are two reasons to think of

First, if you change the original array, the converted array may not be valid for example

Object[] a = {"12","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 selected is very simple, but if you have a very large object [] array and the compiler doesn't know how to fill it, it can't verify that every element of the array satisfies the conversion

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.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>