import java.util.*;
class EnumSetDemo
{
enum Weekdays
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
}
public static void main(String[] args)
{
EnumSet set = null; // LINE A
System.out.println(set);
set = EnumSet.of(Weekdays.Monday); // LINE B
System.out.println("set when added monday : " + set);
set = EnumSet.of(Weekdays.Tuesday); // LINE C
System.out.println("set when added tuesday : " + set);
EnumSet weekends = EnumSet.of(Weekdays.Saturday, Weekdays.Sunday); // LINE D
System.out.println("weekends : " + weekends);
EnumSet otherweekdays = EnumSet.complementOf(weekends); // LINE E
System.out.println("Otherdays : " + otherweekdays);
set = EnumSet.allOf(Weekdays.class); // LINE F
EnumSet setCopy = EnumSet.copyOf(set); // LINE G
System.out.println("setCopy elements : " + setCopy);
}
}
null
set when added monday : [Monday]
set when added tuesday : [Tuesday]
weekends : [Saturday, Sunday]
Otherdays : [Monday, Tuesday, Wednesday, Thursday, Friday]
setCopy elements : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
In the above program we demonstrated how EnumSet
works. At LINE A
we created a null EnumSet
and displayed it. At LINE B
we added Monday
to set using Of
method and displayed. At LINE C
we added Tuesday
to set using the same Of
method which replaced Monday
in the set. At LINE D
we created weekends
a EnumSet
and added Saturday
, Sunday
and displayed it. At LINE E
we created otherweekdays
which don't have the weekends using complementOf
method and then added all the elements in the enum
Weekdays
to set using allOf method
at LINE F
and created a copy of set
as setCopy
using copyOf
method at LINE G
and displayed it.
set.add("Birthday");
System.out.println(set == setCopy);
false
since set
and setCopy
are not referring to Set.
System.out.println(set.equals(setCopy));
true
since set
and setCopy
contains same elements.