What is the EnumSet.contains method in Java?
EnumSet is similar to Set, except that the EnumSet only contains the Enum type as elements. In addition, all the elements must belong to the same Enum type.
For a detailed review of the EnumSet module, refer here.
The EnumSet.contains() method can be used to check if an Enum element is present in the EnumSet object.
Syntax
public boolean contains(Object o)
Argument
The Enum element, which is to be checked for presence in the EnumSet object.
About the method
This method returns true if the element is present in the set. Otherwise, it will return false.
Code
import java.util.EnumSet;class Contains {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("\n set.contains(Size.SMALL) " + set.contains(Size.SMALL));System.out.println("\n set.contains(Size.LARGE) " + set.contains(Size.LARGE));}}
In the above code, we see the following steps:
-
In line
1, we import theEnumSetclass. -
In line
3, we create anEnumwith the nameSize. -
In line
7, we create a newEnumSetobject using theofmethod. We then pass theSize.SMALLandSize.MEDIUMas an argument to theofmethod. Theofmethod will return anEnumSetobject, which will containSize.SMALLandSize.MEDIUMenum elements. -
In line
9, we use theEnumSet.contains()method to check if theEnumelementSize.SMALLis present in theset. Since the is present in theelement In this case, the element “SMALL” set,trueis returned. -
In line
10, we use theEnumSet.contains()method to check if theEnumelementSize.LARGEis present in theset. Since the is present in theelement In this case, the element is “LARGE” set,falseis returned.