在Java中列出类的toArray-为什么我不能将“Integer”列表转换为“Integer”数组?

时间:2022-10-24 21:04:46

I defined List<Integer> stack = new ArrayList<Integer>();

我定义了List stack = new ArrayList ();

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

为什么?它与Integer完全相同 - Integer。当这些类是父子关系时,它不像这种通用情况

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?

问题是什么?

3 个解决方案

#1


11  

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.

由于类型擦除,ArrayList在运行时不知道它的泛型类型,因此它只能为您提供最通用的Object []。您需要使用另一个toArray方法,该方法允许您指定所需的数组类型。

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

#2


2  

The way to do it is this:

这样做的方法是这样的:

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

For the record, the reason that your code doesn't compile is not just type erasure. The problem is that List<T>.toArray() returns an Object[] and it has done this before generics were introduced.

对于记录,您的代码不编译的原因不仅仅是类型擦除。问题是List .toArray()返回一个Object [],它在引入泛型之前就已经完成了。

#3


1  

Do this instead:

改为:

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

We need to pass the "seed" array as an argument to the toArray method.

我们需要将“seed”数组作为参数传递给toArray方法。

#1


11  

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.

由于类型擦除,ArrayList在运行时不知道它的泛型类型,因此它只能为您提供最通用的Object []。您需要使用另一个toArray方法,该方法允许您指定所需的数组类型。

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

#2


2  

The way to do it is this:

这样做的方法是这样的:

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

For the record, the reason that your code doesn't compile is not just type erasure. The problem is that List<T>.toArray() returns an Object[] and it has done this before generics were introduced.

对于记录,您的代码不编译的原因不仅仅是类型擦除。问题是List .toArray()返回一个Object [],它在引入泛型之前就已经完成了。

#3


1  

Do this instead:

改为:

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

We need to pass the "seed" array as an argument to the toArray method.

我们需要将“seed”数组作为参数传递给toArray方法。