EnumSet.complementOf(EnumSet) in Java

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

Syntax:

<K> EnumSet<K> java.util.EnumSet.complementOf(EnumSet<K> s)

This method takes one argument. This method creates an enum set with the same element type as the specified enumset, initially containing all the elements of this type that are not contained in the specified set.

Parameters: One parameter is required for this method.

s: the enum set from whose complement to initialize this enum set.

Returns: The complement of the specified set in this set.

Throws:

NullPointerException - if s is null

Approach 1: When no exception

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

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

        System.out.println("Befor Complement: " + enumSet);
        System.out.println("After Complement: " +
EnumSet.complementOf(enumSet));

    }
}

Output:

Befor Complement: [] After Complement: [RED, GREEN, YELLOW, ORANGE]



Approach 2: NullPointerException 

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

        System.out.println(EnumSet.complementOf(null));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.EnumSet.clone()" because "s" is null at java.base/java.util.EnumSet.copyOf(EnumSet.java:153) at java.base/java.util.EnumSet.complementOf(EnumSet.java:196)


No comments:

Post a Comment