EnumSet 쓸 때 고려해야 할점
- enum 값 들만 포함할 수 있고 모든 value들은 같은 Enum class에 속해 있어야 함
- thread safe하지 않음. 외부에서 사용할 때는 synchronize해주어야 함
- Enum에 선언된 순서대로 element들이 저장됨
- fail-safe iterator를 사용해서 ConcurrentModificationException을 던지지 않음. collection 이 중간에 변경되더라도.
왜 쓰냐
- EnumSet은 다른 Set implementation 보다 선호될 때는 Enum value들을 저장할 때!
이점
- HashSet은 객체를 찾을 때 hashcode를 계산하여 bucket을 찾아내고 객체를 가져오는데 반해, EnumSet은 bitwise indexing으로 객체를 찾아오기에(values are stored in a predictable order) 더 빠름
- bit vectors를 사용하기에 compact and efficient. it uses less memory
사용법
생성방법
public enum Color {
RED, YELLOW, GREEN, BLUE, BLACK, WHITE
}
EnumSet.allOf(Color.class); // 모든 element를 포함
EnumSet.noneOf(Color.class); // empty collection of Color
EnumSet.range(Color.YELLOW, Color.BLUE) ; // [YELLOW, GRREN, BLUE]
EnumSet.complementOf(EnumSet.of(Color.BLACK, Color.WHITE));
// [RED, YELLOW, GREEN, BLUE]
- 나머지 사용방법은 일반 Set의 메서드와 거의 같음
사용예시
public enum UserStatus {
CREATED,
UPDATED,
DELETED;
...
public static final Set<UserStatus> DELETABLE_STATUS =
Collections.unmodifiableSet(EnumSet.of(CREATED, UPDATED));
}