Search code examples
javaarraysobjectcastingpriority-queue

How to cast Object[] into int[] in java


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?


Solution

  • All collections provide an alternative toArray implementation specifying the element type:

    Integer[] objects = pq.toArray(Integer[]::new);
    

    Note this requires Java v11 or higher

    https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)

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