Write a Java program to add Elements of an EnumSet collection to the other EnumSet collection


This Java code demonstrates how to add elements to an EnumSet using the addAll() method.

  • The code first creates two EnumSets of type WEEKDAY using the noneOf() method. The enum_set1 is initialized with Monday through Thursday, while enum_set2 is initialized with Friday through Sunday.
  • Next, the code prints the contents of enum_set1 and enum_set2 using System.out.println().
  • Then, the addAll() method is used to add all elements of enum_set2 to enum_set1.
  • Finally, the code prints the contents of enum_set1 and enum_set2 again to show that enum_set1 now contains all seven days of the week.
  • The WEEKDAY enum defines seven values corresponding to the days of the week.

Source Code

import java.util.*;
public class AddAnother_Element
{
	public static void main(String[] args)
	{
		EnumSet < WEEKDAY > enum_set1 = EnumSet.noneOf(WEEKDAY.class);
		EnumSet < WEEKDAY > enum_set2 = EnumSet.noneOf(WEEKDAY.class);
 
		enum_set1.add(WEEKDAY.Monday);
		enum_set1.add(WEEKDAY.Tuesday);
		enum_set1.add(WEEKDAY.Wednesday);
		enum_set1.add(WEEKDAY.Thursday);
 
		enum_set2.add(WEEKDAY.Friday);
		enum_set2.add(WEEKDAY.Saturday);
		enum_set2.add(WEEKDAY.Sunday);
 
		System.out.println("Elements of EnumSet 1 : " + enum_set1);
		System.out.println("Elements of EnumSet 2 : " + enum_set2);
 
		enum_set1.addAll(enum_set2);
 
		System.out.println("Elements of EnumSet 1 : " + enum_set1);
		System.out.println("Elements of EnumSet 2 : " + enum_set2);
	}
}
enum WEEKDAY {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday 
};

Output

Elements of EnumSet 1 : [Monday, Tuesday, Wednesday, Thursday]
Elements of EnumSet 2 : [Friday, Saturday, Sunday]
Elements of EnumSet 1 : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Elements of EnumSet 2 : [Friday, Saturday, Sunday]