EnumSet removeAll(Collection) in Java

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

Syntax:

boolean java.util.AbstractSet.removeAll(Collection<?> c)

This method takes one argument. This method removes from this set all of its elements that are contained in the specified collection.

Parameters: One parameter is required for this method.

c: a collection containing elements to be removed from this set.

Returns: true if this set changed as a result of the call.

Throws:

1. UnsupportedOperationException - if the removeAll operation is not supported by this set.

2. ClassCastException - if the class of an element of this set is incompatible with the specified collection.

3. NullPointerException - if this set contains a null element and the specified collection does not permit null elements, or if the specified collection is null.

Approach 1: When no exception

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

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

        EnumSet<Colour> enumSet1 = EnumSet.allOf(Colour.class);

        enumSet1.remove(Colour.RED);

        enumSet.removeAll(enumSet1);

        System.out.println(enumSet);

    }
}

Output:

[RED]


Approach 2: NullPointerException 

Java

import java.util.EnumSet;

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

    public static void main(String[] args) {

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

        EnumSet<Colour> enumSet1 = EnumSet.allOf(Colour.class);

        enumSet1.remove(Colour.RED);

        enumSet.removeAll(null);

        System.out.println(enumSet);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.AbstractSet.removeAll(AbstractSet.java:167) at java.base/java.util.RegularEnumSet.removeAll(RegularEnumSet.java:245)


No comments:

Post a Comment