After I use the method .toArray()
in a Priority Queue of Integers I get an array of Objects like this:
Object[] objects = pq.toArray();
However, I need the array to be int[]
. I've tried:
int [] arr = (int[]) objects;
but it says:
Cannot cast from Object[] to int[]
How can I achieve this?
All collections provide an alternative toArray
implementation specifying the element type:
Integer[] objects = pq.toArray(Integer[]::new);
Note this requires Java v11 or higher
Note the resultant array is obviously integer wrapper objects in this case, don't know if that's fine for your requirements.
EDIT - quick test:
PriorityQueue<Integer> q = new PriorityQueue<>();
q.add(42);
System.out.println(Arrays.toString(q.toArray(Integer[]::new)));