Java EnumSet Class Example

EnumSet is a specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient.

EnumSet Class Example

Let's take an example from Effective Java Book. In this example,  we have used basic colors REDGREEN, and BLUE to create a custom color by using EnumSet. EnumSet is very good for combining effects, whether it's text styles e.g. BOLD and UNDERLINE, as described in Effective Java, or combining basic colors to create custom color here. If you have MS paint, you can even test the combination of colors e.g. you can combine REDand BLUE to create YELLOW, combine all three to create WHITE, or combining RED and BLUE to create PINK.
import java.util.EnumSet;
import java.util.Set;

public class EnumSetExample {

    public static void main(final String[] args) {
    // this will draw line in yellow color

        final EnumSet<Color> yellow = EnumSet.of(Color.RED, Color.GREEN);
        drawLine(yellow);

        // RED + GREEN + BLUE = WHITE
        final EnumSet<Color> white = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);
        drawLine(white);
  
        // RED + BLUE = PINK
        final EnumSet<Color> pink = EnumSet.of(Color.RED, Color.BLUE);
        drawLine(pink);

    }

  public static void drawLine(final Set<Color> colors) {
      System.out.println("Requested Colors to draw lines : " + colors);
      for (final Color c : colors) {
          System.out.println("drawing line in color : " + c);
      }
  }

 private enum Color {
     RED(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255);
     private int r;
     private int g;
     private int b;

     private Color(final int r, final int g, final int b) {
         this.r = r;
         this.g = g;
         this.b = b;
    }

    public int getR() {
        return r;
    }

    public int getG() {
        return g;
    }

    public int getB() {
        return b;
    }
  }
}
Output:
Requested Colors to draw lines : [RED, GREEN]
drawing line in color : RED
drawing line in color : GREEN
Requested Colors to draw lines : [RED, GREEN, BLUE]
drawing line in color : RED
drawing line in color : GREEN
drawing line in color : BLUE
Requested Colors to draw lines : [RED, BLUE]
drawing line in color : RED
drawing line in color : BLUE

Reference


Comments