Thursday, October 28, 2010

Related data structure classes: EnumSet and EnumMap

The java.util.EnumSet class provides an efficient implementation of sets of enums as bit maps, or powersets as they were called in Pascal. EnumSet can also generate an Iterable for use with subsets in the for-each statement.
java.util.EnumMap provides an efficient implementation of a map for enums based on an array.

They provide a compact and efficient implementation for enum types. These collections are not synchronized and when used in multi-threaded environment, applications should take care of synchronizing the operations on the collection. EnumMap and EnumSet are homogenous collections of the same enum type. They cannot be used to operate on different enum types at the same time.

public enum Color {
public static EnumSet<Color> getPrimaryColors() {
return EnumSet.of(RED, BLUE, YELLOW);
public static EnumSet<Color> getSecondaryColors() {
return EnumSet.complementOf(getPrimaryColors());

public static void main(String[] args) {
System.out.println("Primary Colors: "+Color.getPrimaryColors());
System.out.println("Secondary Colors: "+Color.getSecondaryColors());
System.out.println("Universe: "+EnumSet.allOf(Color.class));

No comments:

Post a Comment