Write a Java program to Create an empty EnumSet using noneOf() method


This Java code demonstrates the noneOf() method of the EnumSet class, which creates an empty EnumSet of the specified enum type.

  • The code defines an EnumSet enum_set of type WEEKDAY using the allOf() method, which creates an EnumSet containing all of the values of the WEEKDAY enum.
  • The code then prints the contents of enum_set using System.out.println(). This will print all the enum values of WEEKDAY, which are Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.
  • Next, the code defines an empty EnumSet empty_set of type WEEKDAY using the noneOf() method.
  • Finally, the code prints the contents of empty_set using System.out.println(). Since empty_set is empty, nothing will be printed.
  • The WEEKDAY enum defines seven values corresponding to the days of the week.

Source Code

import java.util.*;
public class NoneOf_Method
{
	public static void main(String[] args)
	{
		EnumSet < WEEKDAY > enum_set;
 
		//Adding elements to EnumSet.
		enum_set = EnumSet.allOf(WEEKDAY.class);
		System.out.println("EnumSet : " + enum_set);
 
		EnumSet < WEEKDAY > empty_set = EnumSet.noneOf(WEEKDAY.class);
		System.out.println("Empty EnumSet : " + empty_set);
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

EnumSet : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Empty EnumSet : []