将Object数组转换为Integer数组错误

问题描述 投票:62回答:5

以下代码有什么问题?

Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

代码在最后一行有以下错误:

线程“main”中的异常java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[Ljava.lang.Integer;

java casting
5个回答
88
投票

Ross,你也可以使用Arrays.copyof()或Arrays.copyOfRange()。

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);

在这里击中ClassCastException的原因是你不能将Integer阵列视为Object阵列。 Integer[]Object[]的亚型,但Object[]不是Integer[]

以下也不会给ClassCastException

Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

21
投票

你不能将Object数组转换为Integer数组。你必须循环遍历a的所有元素并单独抛出每个元素。

Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
    c[i] = (Integer) a[i];
}

编辑:我相信这个限制背后的基本原理是,在进行转换时,JVM希望在运行时确保类型安全。由于Objects的数组可以是除Integers之外的任何内容,因此JVM必须执行上述代码所做的操作(单独查看每个元素)。语言设计者决定他们不希望JVM这样做(我不确定为什么,但我确定这是一个很好的理由)。

但是,您可以将子类型数组转换为超类型数组(例如Integer[]Object[])!


14
投票

或者执行以下操作:

...

  Integer[] integerArray = new Integer[integerList.size()];
  integerList.toArray(integerArray);

  return integerArray;

}

4
投票
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

您尝试将一个Object数组转换为强制转换为Array of Integer。你不能这样做。不允许这种类型的向下转发。

您可以创建一个Integer数组,然后将第一个数组的每个值复制到第二个数组中。


1
投票
When casting is done in Java, Java compiler as well as Java run-time check whether the casting is possible or not and throws errors in case not.

When casting of Object types is involved, the instanceof test should pass in order for the assignment to go through. In your example it results
Object[] a = new Object[1]; boolean isIntegerArr = a instanceof Integer[]
If you do a sysout of the above line, it would return false;
So trying an instance of check before casting would help. So, to fix the error, you can either add 'instanceof' check
OR
use following line of code:
(Arrays.asList(a)).toArray(c);

Please do note that the above code would fail, if the Object array contains any entry that is other than Integer.
© www.soinside.com 2019 - 2024. All rights reserved.