비트별 OR를 사용해 여러 상수를 하나의 집합으로 모을 수 있는 집합
여러 컬러가 있고 text에 여러 style을 적용
public class Text{
public static final int STYLE_BOLD = 1 << 0; // 1
public static final int STYLE_ITALIC = 1 << 1; // 2
//0개 이상의 STYLE_* 상수를 비트별 OR한 값
public void applyStyle(int styles){...}
}
//사용 예
text.applyStyles(STYLE_BOLD | STYLE_ITALIC); // 비트 필드
//비트 필드를 대체하는 현대적 기법
public class Text {
public enum Style {BOLD, ITALIC}
// 어떤 Set을 넘겨도 되나, EnumSet이 가장 좋다.
public void applyStyles(Set<Style) styles) { ... }
}
// 사용 예
public static void main(String[] args) {
Text text = new Text();
text.applyStyles(EnumSet.of(Style.BOLD, Style.ITALIC));
}
열거타입의 집합을 사용해야한다면 EnumSet을 사용하도록 하자.
내부에서 비트 벡터로 구현되어있어 성능도 비트 필드에 비견된다.