Java ArrayBlockingQueue toArray() Method

The toArray() method of Java ArrayBlockingQueue returns an array containing all the elements of the ArrayBlockingQueue, in proper sequence.

The next syntax of toArray() returns an array where the runtime of the returned array is that of the specified array, and if the queue fits in the specified array, it is returned therein else a new array is allocated.

Syntax:

Parameters:

  • NA
  • T-the runtime type of an array which contains the collection.
  • a-is an array in which the elements of the ArrayBlockingqueue are stored if it is big enough, otherwise a new array is allocated for the same purpose.

Specified By:

The toArray() method of ArrayBlockingQueue class is specified by:

  • toArray in interface Collection<E>.

Return Value:

The toArray() method returns an array which contains all the elements of the ArrayBlockingqueue.

Example 1

Output:

Element  1: Reema
Element  2: Rahul
Element  3: Rita
Element  4: Ramesh

Example 2

Output:

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

This program is giving error because operator ?>? cannot be applied to java.lang.object.The following example is the solution of this problem.

Example 3

Output:

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

Example 4

Output:

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