List class's toArray in Java- Why can't I convert a list of "Integer" to an "Integer" array?
Asked Answered
V

3

12

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?

Vershen answered 2/9, 2011 at 9:52 Comment(0)
B
16

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()]);
Blubber answered 2/9, 2011 at 9:54 Comment(0)
B
3

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.

Banneret answered 2/9, 2011 at 9:55 Comment(0)
I
2

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.

Ingate answered 2/9, 2011 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.