从对象向下转换为整数运行时错误:java.lang.ClassCastException
运行时异常 - java.lang.ClassCastingException
...
Integer intArr[] = new Integer[arrList.size()];
ArrayList <Integer> arrList =new ArrayList();
intArr=(Integer[])arrList.toArray(); // returns Object class which is downcaste to Integer;
我知道向下转换并不安全,但为什么会发生这种情况? 我还尝试将 ArrayList
转换为 String
到 Integer
到 int
,但我得到了同样的错误。
Run time exception-- java.lang.ClassCastingException
...
Integer intArr[] = new Integer[arrList.size()];
ArrayList <Integer> arrList =new ArrayList();
intArr=(Integer[])arrList.toArray(); // returns Object class which is downcaste to Integer;
I understand down-casting is not safe but why is this happening?
I also tried to converting ArrayList
to String
to Integer
to int
, but I get the same error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试这样做,
您得到的是一个类型化的
Integer
数组,而不是一个对象数组。Try to do this
What you get is a typed
Integer
Array and not a Object array.首先,这不会将 ArrayList 绑定到 Integer 类型。
相反,这就是发生的情况,
arrList
被分配给原始类型的ArrayList
,但这不是问题。问题在于,
由于
arrList
是原始类型(由于赋值,它被编译器分配为new ArrayList
尝试将
arrList
分配给new ArrayList()
并执行以下操作:First of all, this doesn't bind the ArrayList to type
Integer
.Instead, this is what happens,
arrList
is assigned to anArrayList
of raw type, but that isn't a problem.The problem lies in,
since
arrList
is a raw-type (due to the assignment, it gets assigned asnew ArrayList<Object>()
by the compiler), you're effectively getting anObject[]
instead.Try assigning
arrList
tonew ArrayList<Integer>()
and do this:这里的问题是您正在尝试将对象数组转换为整数数组。 Array 本身就是一个对象,
Integer[]
不是ArrayList
的子类,反之亦然。在您的情况下,您需要做的是转换单个项目,如下所示:当然,如果数组列表中的单个元素不是 Integer 类型,您可能会得到 ClassCastException。
The problem here is that you are trying to convert an array of objects to an array of integers. Array is an object in itself and
Integer[]
is not a sub-class ofArrayList
, nor vice versa. What you have to do in your case is cast individual items, something like this:Naturally, you may get ClassCastException if individual elements in the array list are not of type Integer.
toArray(T[] a) 接受一个参数:
“a - 要存储列表元素的数组(如果足够大);否则,是相同 runt 的新数组”
toArray(T[] a)
takes a paramter:"a - the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runt"