Write a Java program to check whether an EnumSet collection is empty or not


The EnumSet class is a specialized Set implementation in Java that is designed to work with enum types. It provides a high-performance implementation of Set for enums, taking advantage of the fact that enums are a finite, well-defined set of values.

  • The code defines an EnumSet enum_set1 of type WEEKDAY using the noneOf() method, which creates an empty EnumSet of the specified enum type.
  • It also defines another EnumSet enum_set2 of type WEEKDAY using the range() method, which creates an EnumSet that includes all of the values between the specified start and end values (inclusive).
  • The code then checks whether enum_set1 and enum_set2 are empty or not using the isEmpty() method, which returns true if the set contains no elements.
  • If enum_set1 is empty, the code prints "EnumSet 1 is an Empty", otherwise it prints "EnumSet 1 is not an Empty". Similarly, if enum_set2 is empty, the code prints "EnumSet 2 is an Empty", otherwise it prints "EnumSet 2 is not an Empty".
  • The WEEKDAY enum defines seven values corresponding to the days of the week.

Source Code

import java.util.*;
public class EmptyNot_Enum
{
	public static void main(String[] args)
	{
		EnumSet < WEEKDAY > enum_set1 = EnumSet.noneOf(WEEKDAY.class);
		EnumSet < WEEKDAY > enum_set2;
 
		enum_set2 = EnumSet.range(WEEKDAY.Wednesday, WEEKDAY.Saturday);
 
		if (enum_set1.isEmpty())
		{
			System.out.println("EnumSet 1 is an Empty");
		}
		else
		{
			System.out.println("EnumSet 1 is not an Empty");
		}
 
		if (enum_set2.isEmpty())
		{
			System.out.println("EnumSet 2 is an Empty");
		}
		else
		{
			System.out.println("EnumSet 2 is not an Empty");
		}
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

EnumSet 1 is an Empty
EnumSet 2 is not an Empty