Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

contains
enumset
java
communitycreator

What is the EnumSet.contains method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

EnumSet is similar to Set except that EnumSet only contains the Enum type as elements. Also, all the elements must be from the same Enum type.

For a detailed review of module EnumSet, 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,

  • In Line 11: Imported the EnumSet class.

  • In Line 33: We have created an Enum with the name Size.

  • In Line 77: Created a new EnumSet object using the of method. We have passed 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 99: We have used the EnumSet.contains() method to check if the Enum element Size.SMALL is present in the set. As the element"SMALL" in this case is present in the set, hence true was returned.

  • In Line 1010: We have used the EnumSet.contains() method to check if the Enum element Size.LARGE is present in the set. As the element"LARGE" in this case is present in the set, hence false was returned.

RELATED TAGS

contains
enumset
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring