Write a Java program to Create an EnumSet using the range() method


This Java code demonstrates the range() method of EnumSet class, which creates an EnumSet that includes all of the values between the specified start and end values (inclusive).

  • The code defines an EnumSet enum_set of type WEEKDAY using the range() method, which creates an EnumSet that includes all of the values between WEEKDAY.Tuesday and WEEKDAY.Saturday (inclusive).
  • The code then prints the contents of enum_set using System.out.println(). This will print all the enum values of WEEKDAY that are between Tuesday and Saturday, which are Tuesday, Wednesday, Thursday, Friday, and Saturday.
  • The WEEKDAY enum defines seven values corresponding to the days of the week.

Source Code

import java.util.*;
public class RangeMethod
{
	public static void main(String[] args)
	{
		EnumSet < WEEKDAY > enum_set;
		enum_set = EnumSet.range(WEEKDAY.Tuesday, WEEKDAY.Saturday);
		System.out.println("EnumSet : " + enum_set);
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

EnumSet : [Tuesday, Wednesday, Thursday, Friday, Saturday]