[JAVA] Item 36: Use EnumSet instead of bit fields

36. Use EnumSet instead of bitfield

When an element of type enum is applied to a set, in the old days, the int enum pattern (Item34) was used to assign the power of 2 to each constant.

// Bit field enumeration constants - OBSOLETE!
public class Text {
    public static final int STYLE_BOLD          = 1 << 0;  // 1
    public static final int STYLE_ITALIC        = 1 << 1;  // 2
    public static final int STYLE_UNDERLINE     = 1 << 2;  // 4
    public static final int STYLE_STRIKETHROUGH = 1 << 3;  // 8
 // Parameter is bitwise OR of zero or more STYLE_ constants
    public void applyStyles(int styles) { ... }
}

By applying OR operation to these, some elements were put together in a set. (Bit field)

text.applyStyles(STYLE_BOLD | STYLE_ITALIC);

Joining and intersecting can be realized by bit operation, but this method inherits all the bad points of int enum.

You should use the EnumSet class to create a set of constants. Performance is not inferior to processing in bit field. The above example uses enum and EnumSet below.

// 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) { ... }
}

enumsetThe client-side code that passes the instance is as follows.

text.applyStyles(EnumSet.of(Style.BOLD, Style.ITALIC));

The 'applyStyles``` method above takes `Setas an argument instead ofEnumSet. Most users will pass EnumSet```, but this is done according to the principle of accepting an interface (Item64) rather than accepting an implementation class as an argument.

Recommended Posts

Item 36: Use EnumSet instead of bit fields
Item 37: Use EnumMap instead of ordinal indexing
Use enum instead of int constant
Item 71: Avoid unnecessary use of checked exceptions
Item 72: Favor the use of standard exceptions
[Java] Why use StringUtils.isEmpty () instead of String.isEmpty ()
[Java] use Optional instead of if (hoge! = null) {...}
Item 44: Favor the use of standard functional interfaces
Item 90: Consider serialization proxies instead of serialized instances
Why use setters/getters instead of public/private in Java
Use of Date class
Item 52: Use overloading judiciously
Item 53: Use varargs judiciously
Item 45: Use streams judiciously