EnumSet.of(K, K...) in Java

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

Syntax:

<K> EnumSet<Colour> java.util.EnumSet.of(K first, K... rest)

This method takes two arguments. This method creates an enum set initially containing the specified elements.

Parameters: Two parameters are required for this method.

first: an element that the set is to contain initially.

rest: the remaining elements the set is to contain initially.

Returns: an enum set initially containing the specified elements.

Throws:

NullPointerException - if any of the specified elements are null,or if rest is null

Approach 1: When no exception

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

        EnumSet<Colour> enumSet;

        Colour[] list = { Colour.GREEN, Colour.YELLOW,
Colour.ORANGE };
        enumSet = EnumSet.of(Colour.RED, list);
        System.out.println(enumSet);

    }
}

Output:

[RED, GREEN, YELLOW, ORANGE]


Approach 2: NullPointerException 

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

        EnumSet<Colour> enumSet;

        Colour[] list = null;
        enumSet = EnumSet.of(Colour.RED, list);
        System.out.println(enumSet);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "<local3>" is null at java.base/java.util.EnumSet.of(EnumSet.java:341)


No comments:

Post a Comment