What is the enumSet.add method in Java?
An
enumSetis similar to aSet, except that anenumSetonly contains theenumtype as elements. All of the elements must also be from a singleenumtype. 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
EnumSetclass. -
In line 3: We created an
Enumwith the nameSize. -
In line 7: We created a new
EnumSetobject using theofmethod. We passed theSize.SMALLas an argument to theofmethod. Theofmethod will return anEnumSetobject that contains aSize.SMALLenumelement. -
In line 9: We used the
addmethod to add theenumelementSize.MEDIUMto theset.