Item 32 - Use EnumSet instead of bit fields
From Effective Java 2/e by Joshua Bloch
Bit field
The bit field representation also lets you perform set operations such as union and intersection efficiently using bitwise arithmetic
// Bit field enumeration constants - OBSOLETE!
public class Text {
public static final int STYLE_BOLD
public static final int STYLE_ITALIC
public static final int STYLE_UNDERLINE
public static final int STYLE_STRIKETHROUGH = 1 << 3; // 8
// Parameter is bitwise OR of zero or more STYLE_ constants
public void applyStyles(int styles) { ... }
}
text.applyStyles(STYLE_BOLD | STYLE_ITALIC);
EnumSet
// EnumSet - a modern replacement for bit fields
public class Text {
public enum Style { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH }
// Any Set could be passed in, but EnumSet is clearly best
public void applyStyles(Set<Style> styles) { ... }
}
text.applyStyles(EnumSet.of(Style.BOLD, Style.ITALIC));
Advantages
- This class implements the Set interface, providing all of the richness, type safety, and interoperability you get with any other Set implementation.
- The EnumSet class combines the conciseness and performance of bit fields
- All the many advantages of enum types