What is the EnumSet.remove method in Java?
The remove method is used to remove an enum element from the EnumSet object.
EnumSetis similar toSet, except thatEnumSetonly contains theenumtype as elements. Also, all the elements must be from a singleenumtype. 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
EnumSetclass. -
In line 3: We create an
Enumwith the nameSize. -
In line 7: We use the
ofmethod to create a newEnumSetobject. We passSize.SMALLandSize.MEDIUMas arguments to theofmethod. Theofmethod will return anEnumSetobject that contains theSize.SMALLandSize.MEDIUMenumelements. -
In line 10: We use the
removemethod to removeSize.SMALLfrom theset. The element is present in theset, so it is removed andtrueis returned. -
In line 11: We use the
removemethod to removeSize.LARGEfrom theset. The element is not present in theset, sofalsewill be returned and thesetremains unchanged.