7

I was trying to convert an ArrayList of Integer to Integer[]

Integer[] finalResult = (Integer[]) result.toArray();

but I got an exception

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

Help me out please.

0

6 Answers 6

10

You need to use the version of toArray() that accepts a generic argument:

Integer[] finalResult = new Integer[result.size()];
result.toArray(finalResult);

or, as a one-liner:

Integer[] finalResult = result.toArray(new Integer[result.size()]);
Sign up to request clarification or add additional context in comments.

Comments

6

You cannot cast List to an array, because a List is not an array. Here are two methods for converting a List<Integer> to an Integer[].

List<Integer> list = Arrays.asList(1, 2, 3);
Integer[] arr = list.toArray(new Integer[list.size()]);
Integer[] arr2 = list.stream().toArray(Integer[]::new); // Java 8 only

Comments

3

List.toArray() returns an Object array. Use List.toArray(T[]) instead:

Integer[] finalResult = (Integer[]) result.toArray(new Integer[result.size()]);

1 Comment

No need for the cast. The return type is already T[], which gets bound at compile time to Integer[].
2

You need to initialize array. Try like this

Integer[] finalResult = new Integer[result.size()];
finalResult = result.toArray(finalResult);

Comments

2

you can do it in multiple ways:

1st method

List<T> list = new ArrayList<T>();

T [] countries = list.toArray(new T[list.size()]);

example:

List<String> list = new ArrayList<String>();

list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");

String [] countries = list.toArray(new String[list.size()]);

2nd method

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

3rd method

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

you can also find some example codes here - http://www.tutorialspoint.com/java/util/arraylist_toarray.htm or http://examples.javacodegeeks.com/core-java/util/list/java-list-to-array-example/

2 Comments

You need to get rid of myArray = new String(); in the 4th method.
I got to know a new method for Java 8-list.stream from your answer. +1'd your answer for that
0

The answers here are using list.size() inside toArray() method for some reason which isn't needed at all. You can just pass an empty integer array with size 0.

It is simple and easy. Take a look:

List<Integer> yourList = List.of(1, 2, 3, 4, 5);
Integer[] intArray = yourList.toArray(new Integer[0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.