toArray(IntFunction): This method is available in java.util.EnumSet 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.EnumSet;import java.util.function.IntFunction;public class EnumSettoArray2 {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumSet<Colour> enumSet = EnumSet.allOf(Colour.class);IntFunction<Colour[]> intFunction =new IntFunction<EnumSettoArray2.Colour[]>() {@Overridepublic Colour[] apply(int value) {Colour[] colours = { Colour.RED, Colour.GREEN };return colours;}};System.out.println(Arrays.toString(enumSet.toArray(intFunction)));}}
Output:
[RED, GREEN, YELLOW, ORANGE]
Approach 2: NullPointerException
Java
import java.util.Arrays;import java.util.EnumSet;import java.util.function.IntFunction;public class EnumSettoArray2 {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumSet<Colour> enumSet = EnumSet.allOf(Colour.class);IntFunction<Colour[]> intFunction = null;System.out.println(Arrays.toString(enumSet.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