Menu
Topics Index
...
`

EnumSetDemo - Java Example Program


EnumSetDemo
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);
    }
}
OUTPUT

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]

DESCRIPTION

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.

THINGS TO TRY
  • Add another Birthday to set using add method. Use the below sample code
    set.add("Birthday");
    The above code throws java.lang.ClassCastException: since the elements in the EnumSet must come from a single enum type.
  • Check whether set and setCopy are equal using == operator and equals method. Use the below sample code.
    System.out.println(set == setCopy);
    The output for the above code is false since set and setCopy are not referring to Set.
    System.out.println(set.equals(setCopy));
    The output for the above code is true since set and setCopy contains same elements.

© meritcampus 2019

All Rights Reserved.

Open In App