Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the EnumSet.isEmpty 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. Additionally, all the elements must be from a single enum type. For further details on EnumSet, refer to this shot.

The isEmpty method can be used to check if the EnumSet object is emptycontains no elements.

Syntax

public boolean isEmpty()

Parameters

This method doesn’t take any parameters.

Return value

isEmpty() returns true if the EnumSet object is empty; otherwise, it returns false.

Code

import java.util.EnumSet;
class isEmpty {
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
public static void main( String args[] ) {
EnumSet<Size> set = EnumSet.allOf(Size.class);
System.out.println("The set is " + set);
System.out.println("set.isEmpty : " + set.isEmpty());
set.clear();
System.out.println("\nThe set is " + set);
System.out.println("set.isEmpty : " + set.isEmpty());
}
}

Explanation

In the code above:

  • In line 1, we import the EnumSet class.

  • In line 3, we create an Enum with the name Size.

  • In line 7, we use the allOf method to create a new EnumSet object. The returned object will contain all of the elements in the specified element type. In our case, the returned set contains all the elements of Size.

  • In line 9, we use the isEmpty method to check if the set is empty. In this case, isEmpty returns false because the set contains all the elements of Size.

  • In line 11, we use the clear method to delete all elements present in the set.

  • In line 13, we use the isEmpty method to check if the set is empty. In this case, isEmpty returns true because the set is empty.

RELATED TAGS

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