Java 9에서는 Collections API에 팩토리 메서드(factory methods)가 새롭게 추가되었습니다. 이를 활용하면 수정 불가능한(unmodifiable) 리스트, 셋, 맵 객체를 간결하게 생성할 수 있어 코드의 줄 수를 크게 줄일 수 있습니다. List.of(), Set.of(), Map.of(), Map.ofEntries()와 같은 정적 팩토리 메서드(static factory methods)는 불변(immutable) 컬렉션을 손쉽게 만들 수 있는 편리한 방법을 제공합니다.
컬렉션 팩토리 메서드의 주요 조건
- 구조적으로 불변(structurally immutable)입니다.
- null 요소나 null 키를 허용하지 않습니다.
- 모든 요소가 직렬화 가능하다면 컬렉션 자체도 직렬화(serializable)할 수 있습니다.
- 생성 시점에 중복된 요소나 키를 거부합니다.
- Set 요소의 반복 순서는 지정되지 않으며, 언제든지 변경될 수 있습니다.
- 값 기반(value-based)으로 동작합니다. 팩토리는 새 인스턴스를 생성하거나 기존 인스턴스를 자유롭게 재사용할 수 있으므로, 이러한 인스턴스에 대한 동일성(identity) 기반 연산, identity 해시 코드, 동기화는 신뢰할 수 없으며 사용을 피하는 것이 좋습니다.
문법(Syntax)
List.of(elements...)
Set.of(elements...)
Map.of(k1, v1, k2, v2)
예제 코드
import java.util.Set;
public class CollectionsTest {
public static void main(String args[]) {
System.out.println("Java 9 Introduced a static factory method: of()");
Set<String> immutableCountrySet = Set.of("India", "England", "South Africa", "Australia");
System.out.println(immutableCountrySet);
try {
immutableCountrySet.add("Newzealand");
} catch(Exception e) {
System.out.println("Caught Exception, Adding Entry to Immutable Collection!");
}
}
}
위 예제에서는 Set.of() 메서드를 사용하여 네 개의 국가 이름을 담은 불변 셋을 생성합니다. 이후 add() 메서드로 새로운 요소를 추가하려고 시도하면, 불변 컬렉션이므로 예외가 발생하고 catch 블록에서 이를 처리하는 것을 확인할 수 있습니다.
실행 결과
Java 9 Introduced a static factory method: of()
[South Africa, India, Australia, England]
Caught Exception, Adding Entry to Immutable Collection!
이처럼 Java 9의 컬렉션 팩토리 메서드를 활용하면 불변 컬렉션을 한 줄로 간단하게 생성할 수 있으며, 실수로 인한 데이터 변경을 컴파일 타임이 아닌 런타임에서 명확하게 방어할 수 있다는 장점이 있습니다.