Search code examples
javaarrayspriority-queue

PriorityQueue to Integer array


Any better way to convert PriorityQueue<int[]> pq to int[pq.size()][pq.peek().length]?

pq.toArray() gives an Object array and I am not so sure how to cast it to an int array.

One way I have tried is this :

PriorityQueue<int[]> pq = new PriorityQueue<int[]>();
int[] fin = new int[pq.size()];
for(int i=0;i<pq.size();i++) {
    fin[i] = pq.remove();
}

But I am looking for better time optimised solution.


Solution

  • The PriorityQueue implements Collection#toArray(T[] a) that you can use like this:

    int[][] fin = pq.toArray(new int[0][0]);
    

    Note that according to your question, you used the untyped version of toArray() which takes no argument and returns Object[]. This would be equivalent to toArray(new Object[0]).