Java 中列表类的 toArray - 为什么我不能将“整数”列表转换为“整数”列表?到“整数”大批?
我定义了 List
当我尝试通过以下方式将其转换为数组时:
Integer[] array= stack.toArray();
我收到此异常:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from Object[] to Integer[].
为什么?它是完全相同的类型——整数到整数。这不像在这种一般情况下,类是 父子关系
我尝试进行转换:
Integer[] array= (Integer[]) stack.toArray();
但在这里我收到此错误:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
问题是什么?
I defined List<Integer> stack = new ArrayList<Integer>();
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[].
Why? It is exactly the same type- Integer to Integer. It's not like in this generic case when the classes are father-and-son relation
I tried to do casting:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于类型擦除,ArrayList在运行时不知道它的泛型类型,因此它只能给你最通用的Object[]。您需要使用 另一个 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.
这样做的方法是这样的:
根据记录,您的代码无法编译的原因不仅仅是类型擦除。问题是
List.toArray()
返回一个Object[]
并且它在引入泛型之前就已经这样做了。The way to do it is this:
For the record, the reason that your code doesn't compile is not just type erasure. The problem is that
List<T>.toArray()
returns anObject[]
and it has done this before generics were introduced.这样做:
我们需要将“种子”数组作为参数传递给
toArray
方法。Do this instead:
We need to pass the "seed" array as an argument to the
toArray
method.