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.
public boolean contains(Object o)
The Enum
element, which is to be checked for presence in the EnumSet
object.
This method returns true
if the element is present in the set
. Otherwise, it will return false
.
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 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 of
method. We then pass the Size.SMALL
and Size.MEDIUM
as an argument to the of
method. The of
method will return an EnumSet
object, which will contain Size.SMALL
and Size.MEDIUM
enum elements.
In line 9
, we use the EnumSet.contains()
method to check if the Enum
element Size.SMALL
is present in the set
. Since the element is present in the set
, true
is returned.
In line 10
, we use the EnumSet.contains()
method to check if the Enum
element Size.LARGE
is present in the set
. Since the element is present in the set
, false
is returned.