Reputation: 376
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?
Upvotes: 0
Views: 1228
Reputation: 3098
It's all written in the javadoc:
Integer[] b = a.toArray(new Integer[0]);
Upvotes: 2
Reputation: 54
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);
Upvotes: 1
Reputation: 201439
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));
Upvotes: 3