What is the enumSet.add method in Java?

An enumSet is similar to a Set, except that an enumSet only contains the enum type as elements. All of the elements must also be from a single enum type. For further details, refer here.

The add method can be used to add an enum element to the enumSet object. The enum element is only added if it is not already present in the enumSet object.

Syntax

public boolean add(enum e)

Parameters

This method takes the enum element e to be added as an argument.

Return value

This method returns true if the element is added to the set. Otherwise, false will be returned.

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);
System.out.println("The set is " + set);
set.add(Size.MEDIUM);
System.out.println("\nThe set is " + set);
}
}

Explanation

In the above code:

  • In line 1: We imported the EnumSet class.

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

  • In line 7: We created a new EnumSet object using the of method. We passed the Size.SMALL as an argument to the of method. The of method will return an EnumSet object that contains a Size.SMALL enum element.

  • In line 9: We used the add method to add the enum element Size.MEDIUM to the set.

Free Resources