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 elements are in no particular order.

Syntax

public Object[] toArray()

Parameters

No parameter is required.

Return Value

Returns an array containing all elements of the queue.

Exception

NA

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);
    PQueue.add(50);

    //convert the priority queue into an array
    Object[] Arr =  PQueue.toArray();

    //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 50 

❮ Java.util - PriorityQueue