没有错误
Object[] a = new String[]{"12","34","56"}; String[] b = (String[]) a;
没有错误
Object a = new String[]{"12","34","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","34","56"}; String[] b = (String[]) a;
当然,如果 Object[]
变量是作为 String[]
创建的,我们可以将它向下转换回 String[]
。
我的问题是为什么我们不能将 Object[]
转换为 String[]
当它被创建为 Object[]
但它的所有成员是字符串?是出于安全原因还是实现此功能没有太大用处?
最佳答案
这是我能想到的两个原因。
首先,如果您更改原始 数组,则转换后的数组可能会变得无效。例如
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[]
数组并且编译器不清楚填充它的是什么,那么它就没有办法验证数组的每个元素都满足转换。
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.
关于java - 为什么不能将 Object[] 转换为 String[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18119494/