EnumSet retainAll(Collection) in Java

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

Syntax:

boolean java.util.AbstractCollection.retainAll(Collection<?> c)

This method takes one argument. This method retains only the elements in this collection that are contained in the specified collection.

Parameters: One parameter is required for this method.

c: a collection containing elements to be retained in this collection.

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

Throws:

1. UnsupportedOperationException - if the retainAll operation is not supported by this collection.

2. ClassCastException - if the types of one or more elements in this collection are incompatible with the specified collection.

3. NullPointerException - if this collection contains one or more null elements 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 EnumSetretainAll {
    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.retainAll(enumSet1);

        System.out.println(enumSet);

    }
}

Output:

[GREEN, YELLOW, ORANGE]


Approach 2: NullPointerException 

Java

import java.util.EnumSet;

public class EnumSetretainAll {
    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.retainAll(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.AbstractCollection.retainAll(AbstractCollection.java:399) at java.base/java.util.RegularEnumSet.retainAll(RegularEnumSet.java:266)


No comments:

Post a Comment