What is the PriorityQueue.toArray() method in Java?

In this shot, we will learn how to use the PriorityQueue.toArray() method in Java.

Introduction

The PriorityQueue.toArray() method is used to create an array object with the same elements as those present in the PriorityQueue class.

The PriorityQueue.toArray() method is present in the PriorityQueue class inside the java.util package.

Syntax

The syntax of the PriorityQueue.toArray() function is given below:

public Object[] toArray();

Parameters

The PriorityQueue.toArray() method does not accept any parameters.

Return value

The PriorityQueue.toArray() method returns the array with the same elements that are present in the PriorityQueue class.

Code

Let’s look at the code now.

import java.util.*;
class Main
{
public static void main(String[] args)
{
PriorityQueue<Integer> p = new PriorityQueue<Integer>();
p.add(2);
p.add(28);
p.add(6);
p.add(80);
p.add(28);
p.add(7);
p.add(15);
Object[] a=p.toArray();
System.out.print("Elements of the array are: ");
for(int i = 0; i < a.length; i++)
System.out.print( a[i] + " ");
}
}

Code explanation

  • In line 1, we import the required package.

  • In line 2, we make a Main class.

  • In line 4, we make a main() function.

  • In line 6, we declare a PriorityQueue that consists of Integer type elements.

  • From lines 8 to 14, we use the PriorityQueue.add() method to insert the elements in the PriorityQueue class.

  • In line 16, we use the PriorityQueue.toArray() method to create an array object of the same elements as those present in the PriorityQueue class.

  • In lines 20 and 21, we display the elements of the array. Here, we can verify that the elements in the array object are the same as the ones present in the PriorityQueue class.