What is the EnumSet.clear method in Java?

EnumSet is similar to a Set, except in the fact that an EnumSet only contains the Enum type as elements. Additionally, all the elements in an EnumSet always come from the same Enum type.

For a detailed review of theEnumSet module, please click here.

The EnumSet.clear() method can be used to delete all the elements present in the EnumSet object.

Syntax

public void clear()

About the method

This method neither takes any arguments nor returns any value(s). It just removes all the memory that is occupied by the elements of a particular Enumset object.

Code

import java.util.EnumSet;
class isEmpty {
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
public static void main( String args[] ) {
EnumSet<Size> set = EnumSet.allOf(Size.class);
System.out.println("The set is " + set);
set.clear();
System.out.println("After using set.clear()\nThe set is " + set);
}
}

In the above code,

  • In line 1: We import the EnumSet class.

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

  • In line 7: We create a new EnumSet object using the allOf method. We pass the Size.class as an argument to the allOf method, which returns an EnumSet object containing all the elements of the Size Enum.

  • In line 9: We use the clear method to delete all the elements present in the set, as that will make the set empty.

Free Resources