EnumSet


  • EnumSet birth is in java 1.5
  • EnumSet extends AbstractSet class
  • EnumSet implements Serializable, Cloneable, Iterable<E>, Collection<E>, Set<E> interfaces
  • It is specialized Set implementation to use with enum type values.
  • All the keys in an EnumSet must belong to the single enum type that is specified when the EnumSet is created.
  • Internally EnumSet are represented as Vectors.
  • EnumSet representation is very efficient and compact.
  • EnumSet maintained in the natural order of their keys
  • (the order in which the enum constants are declared).
  • The Iterator returned by the EnumSet is weakly consistent.
  • The Iterator will never throw ConcurrentModificationException.
  • Null elements are not permitted. 
  • Attempt to insert a null element will throw NullPointerException. 
  • EnumSet is not synchronized.
  • All the basic operations are execute in constant time. 
  • All operations are likely (though it is not guaranteed) to be more faster than HashSet.
  • Bulk operations (containsAll, ratailAll) executes very quickly if their argument is an enum set.
Create Synchronized EnumSet
Set<DayEnum> enumSet = Collections.synchronizedSet(EnumSet.noneOf(DayEnum.class));

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.EnumSet;
import java.util.Set;

public class EnumSetTest {

    enum Day{        SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY;}

    public static void main(String[] args){

        Set<Day> enumSet  = EnumSet.noneOf(Day.class);

        enumSet.add(Day.SUNDAY);
        enumSet.add(Day.MONDAY);
        enumSet.forEach((day)->{System.out.println(day);});

    }
}