ArrayList's toArray() Method not Working Properly

nishantc1527 :

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?

Elliott Frisch :

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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326715&siteId=1