Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<Integer> to Integer[] in java?

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.

like image 683
Kenny Avatar asked Nov 29 '15 06:11

Kenny


People also ask

What does int [] do in Java?

Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].

How do you convert a list to an array in Java?

The best and easiest way to convert a List into an Array in Java is to use the . toArray() method. Likewise, we can convert back a List to Array using the Arrays. asList() method.

Can we convert integer array to integer in Java?

Apache Commons Lang's ArrayUtils class provides toPrimitive() method that can convert an Integer array to primitive ints.


1 Answers

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()]);
like image 154
Ted Hopp Avatar answered Oct 07 '22 23:10

Ted Hopp