列表类的指定者:Java的为什么我不能转换的&QUOT列表;整数QUOT;到"整数QUOT;数组? [英] List class's toArray in Java- Why can't I convert a list of "Integer" to an "Integer" array?

查看:235
本文介绍了列表类的指定者:Java的为什么我不能转换的&QUOT列表;整数QUOT;到"整数QUOT;数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义的列表<整数GT;堆栈=新的ArrayList<整数GT;();

当我试图将其转换为一个数组的方式如下:

When I'm trying to convert it to an array in the following way:

Integer[] array= stack.toArray();

我得到这个异​​常:

I get this exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from Object[] to Integer[].

为什么呢?它是完全一样的类型 - 整数到整数。这不是在这种情况下,一般喜欢当类是<一个href=\"http://stackoverflow.com/questions/7254820/can-i-add-to-a-generic-collection-of-type-a-values-of-type-b-which-extends-a-wi\">father-and-son关系

我试图做铸造:

    Integer[] array= (Integer[]) stack.toArray();

但在这里我得到这个错误:

But here I get this error:

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

这是什么问题?

What is the problem?

推荐答案

,ArrayList中不知道在运行时的泛型类型,所以只能给你最普遍的对象[]。您需要使用其他方法的toArray 它允许你指定你想要的阵列的类型。

Because of type erasure, the ArrayList does not know its generic type at runtime, so it can only give you the most general Object[]. You need to use the other toArray method which allows you to specify the type of the array that you want.

Integer[] array= stack.toArray(new Integer[stack.size()]);

这篇关于列表类的指定者:Java的为什么我不能转换的&QUOT列表;整数QUOT;到&QUOT;整数QUOT;数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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