我正在使用Java来了解它是如何工作的,但我对某些类型的铸件有一些疑问。请考虑以下代码:
String[][] s = null;
Object[] o = null;
o = (Object[][]) s; // compile-time correct现在,考虑以下示例:
Object[][] o = null;
String[] s = null;
s = (String[]) o; // compile-time error: Cannot cast from Object[] to String[]为什么会发生这种事?我很困惑。
发布于 2016-07-12 21:02:03
它之所以失败,是因为它确实是错误的(即总是而且只能是错误的)。
o必须包含对象数组。这不可能是弦乐。
在第一个示例中,可以将字符串数组键入为对象。
如果我们删除一个“数组嵌套”,我们就可以说明这一点。考虑:
String[] myStringArray = null; //instantiation not important
Object someObj = myStringArray; //no problem since arrays are Objects在第二个例子中,您所做的就是
Object[] myObjectArray = null; //instantiation not important
String someString = myObjectArray; //compile time error, since an Object[] is never a String发布于 2016-07-12 20:59:18
请注意,这并没有给出编译错误:
Object[] o = null;
String[] s = null;
s = (String[]) o;Object[][]到String[]将产生不兼容的类型错误。
Object[]到String[]将正常工作。
https://stackoverflow.com/questions/38338723
复制相似问题