EnumSet.of(K) in Java

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

Syntax:

<K> EnumSet<K> java.util.EnumSet.of(K e)

This method takes one argument. This method creates an enum set initially containing the specified element.

Parameters: One parameter is required for this method.

e: the element that this set is to contain initially.

Returns: an enum set initially containing the specified element.

Throws:

NullPointerException - if e is null

Approach 1: When no exception

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

        EnumSet<Colour> enumSet;

        enumSet = EnumSet.of(Colour.GREEN);
        System.out.println(enumSet);

    }
}

Output:

[GREEN]


Approach 2: NullPointerException 

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

        EnumSet<Colour> enumSet;

        enumSet = EnumSet.of(null);
        System.out.println(enumSet);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Enum.getDeclaringClass()" because "e" is null at java.base/java.util.EnumSet.of(EnumSet.java:216)


No comments:

Post a Comment