将对象数组转换为整数数组错误 [英] casting Object array to Integer array error

查看:35
本文介绍了将对象数组转换为整数数组错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有什么问题?

What's wrong with the following code?

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

代码最后一行有如下错误:

The code has the following error at the last line :

线程main"中的异常java.lang.ClassCastException:[Ljava.lang.Object;不能转换为 [Ljava.lang.Integer;

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

推荐答案

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

Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.

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[].

Here the reason to hitting an ClassCastException is you can't treat an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

以下也不会给出ClassCastException.

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

这篇关于将对象数组转换为整数数组错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆