What is the EnumSet.remove method in Java?

The remove method is used to remove an enum element from the EnumSet object.

EnumSet is similar to Set, except that EnumSet only contains the enum type as elements. Also, all the elements must be from a single enum type. For further details, refer here.

Syntax

public boolean remove(E e)

Parameters

This method takes the enum element to be added as a parameter.

Return value

The remove method returns true if the element is removed from the set. Otherwise, it returns false.

Code

import java.util.EnumSet;
class isEmpty {
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
public static void main( String args[] ) {
EnumSet<Size> set = EnumSet.of(Size.SMALL,Size.MEDIUM);
System.out.println("The set is " + set);
System.out.println("\nset.remove(Size.SMALL). Is element removed " + set.remove(Size.SMALL));
System.out.println("\nset.remove(Size.LARGE). Is element removed " + set.remove(Size.LARGE));
}
}

Explanation

In the code above:

  • In line 1: Import the EnumSet class.

  • In line 3: We create an Enum with the name Size.

  • In line 7: We use the of method to create a new EnumSet object. We pass Size.SMALL and Size.MEDIUM as arguments to the of method. The of method will return an EnumSet object that contains the Size.SMALL and Size.MEDIUM enum elements.

  • In line 10: We use the remove method to remove Size.SMALL from the set. The element is present in the set, so it is removed and true is returned.

  • In line 11: We use the remove method to remove Size.LARGE from the set. The element is not present in the set, so false will be returned and the set remains unchanged.

Free Resources