Java Utility Library

Java PriorityQueue - toArray() Method



The java.util.PriorityQueue.toArray() method returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. If the given queue fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of the given queue.

If the queue fits in the specified array with room to spare, the element in the array immediately following the end of the collection is set to null.

Syntax

public <T> T[] toArray(T[] a)

Here, T is the type of element maintained by the container.


Parameters

a Specify the array into which the elements of the queue are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value

Returns an array containing all elements of the queue.

Exception

  • Throws ArrayStoreException, if the runtime type of a is not a supertype of the runtime type of every element in the queue.
  • Throws NullPointerException, if the given array is null.

Example:

In the example below, the java.util.PriorityQueue.toArray() method returns an array containing all elements of the given queue.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a priority queue
    PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>();

    //populating the priority queue 
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(30);
    PQueue.add(40);

    //creating an empty array
    Integer[] Arr = new Integer[5];

    //convert the priority queue into an array
    PQueue.toArray(Arr);

    //print the array
    System.out.print("The Arr contains: ");
    for(int i = 0; i < Arr.length; i++)
      System.out.print(Arr[i]+ " ");
  }
}

The output of the above code will be:

The Arr contains: 10 20 30 40 null

❮ Java.util - PriorityQueue