EnumSet.noneOf(Class) in Java

EnumSet.noneOf(Class): This method is available in java.util.EnumSet class of Java.

Syntax:

<K> EnumSet<K> java.util.EnumSet.noneOf(Class<K> elementType)

This method takes one argument. This method creates an empty enum set with 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 empty enum set of the specified type.

Throws:

NullPointerException - if elementType is null

Approach 1: When no exception

Java

import java.util.EnumSet;

public class EnumSetnoneOf {
    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumSet<Colour> enumSet = EnumSet.noneOf(Colour.class);
        System.out.println(enumSet);

    }
}

Output:

[]


Approach 2: NullPointerException 

Java

import java.util.EnumSet;

public class EnumSetnoneOf {
    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumSet<Colour> enumSet = EnumSet.noneOf(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)


No comments:

Post a Comment