问题描述
-
没有错误
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;
运行时错误:ClassCastException
Run time error : ClassCastException
Object[] a = new Object[3];
a[0] = "12";
a[1] = "34";
a[2] = "56";
String[] b = (String[]) a;
运行时错误:ClassCastException
Run time error : ClassCastException
Object[] a = {"12","34","56"};
String[] b = (String[]) a;
当然,如果它是作为 String []
创建的,我们可以将 Object []
变量下放回 String []
.
Of course, we can downcast an Object[]
variable back to String[]
if it was created as an String[]
.
我的问题是为什么当将 Object []
创建为 Object []
时,为什么不能将 Object []
转换为 String []
,成员是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?
推荐答案
这是我能想到的两个原因.
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!
第二,您选择的示例非常简单,但是如果您有一个很大的 Object []
数组,并且编译器不清楚填充它的内容,那么它将无法验证数组的每个元素都满足转换要求.
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.
这篇关于为什么不能将Object []转换为String []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!