EnumSet

EnumSet extends AbstractSet and implements Set. It is specifically for use with keys of an enum type. It is a generic class that has this declaration:

class EnumSet<E extends Enum<E>>

E specifies the elements.

EnumSet defines no constructors. It uses the factory methods to create objects.

The EnumSet class provides a Set implementation that is based on a bitset. Its elements are constants that must come from the same enum. Null elements are not permitted.

The following code use the EnumSet

 
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;

enum Weekday {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class Main {
  public static void main(String[] args) {
    Set<Weekday> daysOff = EnumSet.of(Weekday.SUNDAY, Weekday.MONDAY);
    Iterator<Weekday> iter = daysOff.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());
  }
}
  

import java.util.EnumSet;
import java.util.Iterator;

public class Main {
    
    public static void main(String[] args) {
        EnumSet largeSize = EnumSet.of(Size.XL,Size.XXL,Size.XXXL);
        for(Iterator it = largeSize.iterator();it.hasNext();){
            Size size = (Size)it.next();
            System.out.println(size);
        }
    }
}


enum Size {
  S, M, L, XL, XXL, XXXL;

}

The output:



XL
XXL
XXXL
Home 
  Java Book 
    Collection