toArray(IntFunction): This method is available in java.util.LinkedHashSet 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 that 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.LinkedHashSet;import java.util.function.IntFunction;public class LinkedHashSettoArray2 {public static void main(String[] args) {LinkedHashSet<String> linkedHashSet =new LinkedHashSet<>();linkedHashSet.add("Hello");linkedHashSet.add("Java");IntFunction<String[]> intFunction =new IntFunction<String[]>() {@Overridepublic String[] apply(int value) {String[] string = { "Hello", "C++" };return string;}};System.out.println(Arrays.toString(linkedHashSet.toArray(intFunction)));}}
Output:
[Hello, Java]
Approach 2: NullPointerException
Java
import java.util.Arrays;import java.util.LinkedHashSet;import java.util.function.IntFunction;public class LinkedHashSettoArray2 {public static void main(String[] args) {LinkedHashSet<String> linkedHashSet =new LinkedHashSet<>();linkedHashSet.add("Hello");linkedHashSet.add("Java");IntFunction<String[]> intFunction = null;System.out.println(Arrays.toString(linkedHashSet.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