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 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.

Free Resources