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) { ... }
}
enumset
The 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 of
EnumSet. 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