PriorityQueue toArray(K[]) in Java

toArray(K[]): This method is available in java.util.PriorityQueue class of Java.

Syntax:

<K> K[] java.util.PriorityQueue.toArray(K[] a)

This method takes one argument. This 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.

Parameters: One parameter is required for this method.

a: 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.

Returns: an array containing all of the elements in this queue.

Throws:

1. ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this queue.

2. NullPointerException - if the specified array is null

Approach 1: When no exception

Java

import java.util.Arrays;
import java.util.PriorityQueue;

public class PriorityQueuetoArray3 {
    public static void main(String[] args) {

        PriorityQueue<Integer> priorityQueue =
new PriorityQueue<Integer>();

        priorityQueue.add(12);
        priorityQueue.add(5);
        priorityQueue.add(10);
        priorityQueue.add(2);

        Integer[] a = { 1, 2 };

        System.out.println(Arrays.
toString(priorityQueue.toArray(a)));

    }
}

Output:

[2, 5, 10, 12]


Approach 2: NullPointerException 

Java

import java.util.Arrays;
import java.util.PriorityQueue;

public class PriorityQueuetoArray3 {
    public static void main(String[] args) {

        PriorityQueue<Integer> priorityQueue =
new PriorityQueue<Integer>();

        priorityQueue.add(12);
        priorityQueue.add(5);
        priorityQueue.add(10);
        priorityQueue.add(2);

        Integer[] a = null;

        System.out.println(Arrays.
toString(priorityQueue.toArray(a)));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "a" is null at java.base/java.util.PriorityQueue.toArray(PriorityQueue.java:452)


No comments:

Post a Comment