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.
Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].
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.
Apache Commons Lang's ArrayUtils class provides toPrimitive() method that can convert an Integer array to primitive ints.
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()]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With