0

When looking through ArrayList's methods, I saw a method called toArray(). I tried out this method using the following code:

ArrayList<Integer> a = new ArrayList<>();
// Assigning random elements to the ArrayList
int[] b = a.toArray();

However, this showed the following exception in the compiler:

Incompatible types.
Required: int[]
Found: java.lang.Object[]

The next thing I tried next is down-casting it to int[]

ArrayList<Integer> a = new ArrayList<>();
// Assigning random elements to the ArrayList
int[] b = (int[]) a.toArray();

This showed another error:

Cannot cast java.lang.Object[] to int[]

The last thing I tried is making it an Integer[] instead, and down-casting it to Integer[]

ArrayList<Integer> a = new ArrayList<>();
// Assigning random elements to the ArrayList
Integer[] b = (Integer[]) a.toArray();

This one compiled, but as soon as I ran it it produced ClassCastException. How do I use this toArray() method without errors?

0

3 Answers 3

3

List can only hold reference types (like Integer). Integer is a wrapper type. To convert a List<Integer> to an int[] there is an option using a Stream to map the Integer values to int and then collect to an int[]. Like,

int[] b = a.stream().mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(b));
Sign up to request clarification or add additional context in comments.

Comments

2

It's all written in the javadoc:

Integer[] b = a.toArray(new Integer[0]);

4 Comments

I tried changing this to int[] b = (int[]) a.toArray(new int[0]);, but it said there is no such method for primitive type arrays. Is there any way to do this?
you dont need the cast Integer[] b = a.toArray(new Integer[0]);
@nishantc1527 the reason that you need to pass the stupid new Integer[0] thing is to make it invoke generic version of toArray and let it know which type it should return. Type inference doesn't work with primitive types, so new int[0] won't work. Bottom line is that if you want type safety you should stay away from arrays.
@MK true (for both statements). I usually try to rework my data structures when I find myself needing to call toArray(). Especially for a list of boxed primitives where Java seems terribly cumbersome.
1

Extending the answer of @Matthieu, It seems you need to pass new Integer[]. Attaching an example link given in geeksforgeeks.

Integer[] arr = new Integer[a.size()]; 
arr = a.toArray(arr);

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.