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

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

问题描述

以下代码有什么问题?

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;

The code has the following error at the last line : 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 IS-A对象列表的列表,尽管是整数IS-A(n)对象。

Here the reason to hitting an ClassCastException is you can't treat a list of Integer IS-A list of Object although an Integer IS-A(n) Object.

下面也不会给出 ClassCastException

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

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

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