>没有错误
Object[] a = new String[]{"12","34","56"}; String[] b = (String[]) a;
>没有错误
Object a = new String[]{"12","56"}; String[] b = (String[]) a;
>运行时错误:ClassCastException
Object[] a = new Object[3]; a[0] = "12"; a[1] = "34"; a[2] = "56"; String[] b = (String[]) a;
>运行时错误:ClassCastException
Object[] a = {"12","56"}; String[] b = (String[]) a;
当然,如果一个Object []变量被创建为一个String [],我们可以将其转换回String [].
我的问题是为什么当Object []创建为Object []但它的所有成员都是String时,我们不能将Object []转换为String []是因为安全原因还是对实现这个没有帮助?
解决方法
这里有两个原因可以想到.
首先,如果您更改原始数组,则转换的数组可能无效.例如
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!
其次,您所选择的示例非常简单,但如果您有一个非常大的Object []数组,并且编译器不清楚填充它,那么它无法验证数组的每个元素都满足该转换.
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.