Write a Java program to Create an EnumSet collection from an existing EnumSet collection


This Java code demonstrates the copyOf() method of the EnumSet class, which creates a new EnumSet with the same elements as the specified EnumSet.

  • 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 a new EnumSet new_set of type WEEKDAY using the copyOf() method and passing enum_set as the argument. This creates a new EnumSet that contains the same elements as enum_set.
  • Finally, the code prints the contents of new_set using System.out.println(). This will print all the enum values of WEEKDAY, which are Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.
  • The WEEKDAY enum defines seven values corresponding to the days of the week.

Source Code

import java.util.*;
public class Existing_Enum
 {
	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 > new_set = EnumSet.copyOf(enum_set);
		System.out.println("New EnumSet : " + new_set);
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

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