toArray(IntFunction<K[]>): This method is available in java.util.PriorityQueue class of Java.
Syntax:
<K> K[] java.util.Collection.toArray(IntFunction<K[]> generator)
This method takes one argument. This method returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.
Parameters: One parameter is required for this method.
generator: a function which produces a new array of the desired type and the provided length.
Returns: an array containing all of the elements in this collection.
Throws:
1. ArrayStoreException - if the runtime type of any element in this collection is not assignable to the runtime component type of the generated array.
2. NullPointerException - if the generator function is null.
Approach 1: When no exception
Java
import java.util.Arrays;import java.util.PriorityQueue;import java.util.function.IntFunction;public class PriorityQueuetoArray2 {public static void main(String[] args) {PriorityQueue<Integer> priorityQueue =new PriorityQueue<Integer>();priorityQueue.add(12);priorityQueue.add(5);priorityQueue.add(10);priorityQueue.add(2);IntFunction<Integer[]> intFunction =new IntFunction<Integer[]>() {@Overridepublic Integer[] apply(int value) {Integer[] string = { 1, 2 };return string;}};System.out.println(Arrays.toString(priorityQueue.toArray(intFunction)));}}
Output:
[2, 5, 10, 12]
Approach 2: NullPointerException
Java
import java.util.Arrays;import java.util.PriorityQueue;import java.util.function.IntFunction;public class PriorityQueuetoArray2 {public static void main(String[] args) {PriorityQueue<Integer> priorityQueue =new PriorityQueue<Integer>();priorityQueue.add(12);priorityQueue.add(5);priorityQueue.add(10);priorityQueue.add(2);IntFunction<Integer[]> intFunction = null;System.out.println(Arrays.toString(priorityQueue.toArray(intFunction)));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.function.IntFunction.apply(int)" because "generator" is null at java.base/java.util.Collection.toArray(Collection.java:413)
No comments:
Post a Comment