Javatpoint Logo
Javatpoint Logo

Java PriorityQueue toArray() Method

The toArray() method of PriorityQueue class returns an array containing all the elements present in the queue where the elements are present in no particular order.

The array is returned, if the queue fits in the specified array. Else, a new array is allocated with the same type of the array and size of the queue.

Syntax

Parameter

NA

a - this is the array in which the elements of the queue will be stored.

Type Parameters

T - this is the runtime type of the array to hold the collection.

Specified By

The toArray() method of PriorityQueue class is specified by toArray() method in interface Collection<E>.

Override

The toArray() method of PriorityQueue class isoverrided by toArray() method in class AbstractCollection<E>.

Return Value

The toArray() method returns an array that contains all the elements of this queue.

Example 1

Test it Now

Output:

Element : Rahul
Element : Ramesh
Element : Rita
Element :Reema

Example 2

Test it Now

Output:

Error:(20, 24) java: bad operand types for binary operator '>'
first type:  java.lang.Object
second type: java.lang.Object

Note: Operator ?>? cannot be applied to ?java.lang.object?.

Example 3 is the solution of the above described problem.

Example 3

Test it Now

Output:

Elements : 2 5 17 80 8 
Ascending order : 2 5 8 17 80

Example 4

Test it Now

Output:

Exception in thread "main" java.lang.NullPointerException
	atjava.util.PriorityQueue.toArray(PriorityQueue.java:469)
	at com.javaTpoint.PriorityQueueToArrayExample5.main(PriorityQueueToArrayExample4.java:12)
Next TopicJava PriorityQueue



Help Others, Please Share

facebook twitter pinterest