item36

비트 필드 대신 EnumSet을 사용하라

비트 필드

비트 필드란

열거한 값들이 주로 집합으로 사용될 경우, 각 상수에 서로 다른 2의 거듭제곱 값을 할당한 정수 열거 패턴을 사용할 수 있다. 예시 코드는 아래와 같다.

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 void applyStyles(int styles) {
        if ((styles & STYLE_BOLD) != 0) {
            // Apply bold style
            System.out.println("Applying bold style");
        }
        if ((styles & STYLE_ITALIC) != 0) {
            // Apply italic style
            System.out.println("Applying italic style");
        }
        if ((styles & STYLE_UNDERLINE) != 0) {
            // Apply underline style
            System.out.println("Applying underline style");
        }
    }
    
    public static void main(String[] args) {
        applyStyles(3);
        
        // 출력:
        // Applying bold style
				// Applying italic style
    }
}

비트 필드의 단점

비트 필드를 사용하면 비트별 연산을 사용해 합집합과 교집합 같은 집합 연산을 효율적으로 수행할 수 있다. 하지만 치명적인 단점이 존재한다. 단점은 아래와 같다.

EnumSet

비트 필드 문제의 해결 방안 EnumSet

EnumSet 클래스는 열거 타입 상수의 값으로 구성된 집합을 효과적으로 표현해준다. EnumSet의 특징은 아래와 같다.