EnumSet.allOf(Class): This method is available in java.util.EnumSet class of Java.
Syntax:
<K> EnumSet<K> java.util.EnumSet.allOf(Class<K> elementType)
This method takes one argument. This method creates an enum set containing all of the elements in the specified element type.
Parameters: One parameter is required for this method.
elementType: the class object of the element type for this enumset.
Returns: An enum set containing all the elements in the specified type.
Throws:
NullPointerException - if elementType is null
Approach 1: When no exception
Java
import java.util.EnumSet;public class EnumSetallOf {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumSet<Colour> enumSet = EnumSet.allOf(Colour.class);System.out.println(enumSet);}}
Output:
[RED, GREEN, YELLOW, ORANGE]
Approach 2: NullPointerException
Java
import java.util.EnumSet;public class EnumSetallOf {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumSet<Colour> enumSet = EnumSet.allOf(null);System.out.println(enumSet);}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Class.getEnumConstantsShared()" because "klass" is null at java.base/java.lang.System$2.getEnumConstantsShared(System.java:2170) at java.base/java.util.EnumSet.getUniverse(EnumSet.java:408) at java.base/java.util.EnumSet.noneOf(EnumSet.java:111) at java.base/java.util.EnumSet.allOf(EnumSet.java:132)
No comments:
Post a Comment