为什么不能投的对象[]为String [] [英] why can't cast Object[] to String[]
问题描述
-
没有误差
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 []
如果它创建为一个的String []
。
Of course, we can downcast an Object[]
variable back to String[]
if it was created as an 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!
其次,您所选择的例子很简单,但如果你有一个非常大的对象[]
阵列,它不是明确的编译器是什么加油吧,那么它有没有验证该阵列的每个元素满足投方式。
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.
这篇关于为什么不能投的对象[]为String []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!