본문 바로가기
Dev

[Java] List.of를 사용한 초기화

by kimyoungrok 2025. 2. 9.
728x90

UnsupportedOperationException

Java에서 `List.of()`는 불변 리스트(Immutable List)를 생성합니다. 일반적으로 불변 리스트에 요소를 추가하려고 하면 `UnsupportedOperationException`이 발생합니다

 

예를 들어, 아래 코드는 예외를 발생시킵니다.

List<Integer> list = List.of(0);
list.add(1);  // UnsupportedOperationException 발생!

 


 

List.of()를 사용한 초기화

그러나 다음 코드에서는 List.of()로 생성한 불변 리스트를 초기값으로 설정함에도 불구하고 정상적으로 작동합니다.

PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(0));
pq.add(1);  // 정상 작동

 

 

동작 원리

그렇다면, 불변 리스트를 기반으로 생성된 컬렉션이 작동하는 이유는 무엇일까요?

생성자 내부를 살펴보겠습니다.

내부적으로 initElementsFromCollection을 호출하며 전달받은 불변리스트를 복사한다는 사실을 알 수 있습니다.

public PriorityQueue(Collection<? extends E> c) {
    if (c instanceof SortedSet<?>) {
        ...
    }
    else if (c instanceof PriorityQueue<?>) {
        ...
    }
    else {
        this.comparator = null;
        initFromCollection(c);
    }
}

private void initFromCollection(Collection<? extends E> c) {
    initElementsFromCollection(c);
    heapify();
}

private void initElementsFromCollection(Collection<? extends E> c) {
    Object[] es = c.toArray();
    int len = es.length;
    if (c.getClass() != ArrayList.class)
        es = Arrays.copyOf(es, len, Object[].class);
    if (len == 1 || this.comparator != null)
        for (Object e : es)
            if (e == null)
                throw new NullPointerException();
    this.queue = ensureNonEmpty(es);
    this.size = len;
}

다른 방법

  • new ArrayList<>(List.of())을 사용해 초기화 하는 방법
  • 나중에 요소를 별도로 추가하는 방법

결론

List.of()는 불변 리스트를 생성하지만, 이를 컬렉션의 생성자로 전달하면 내부적으로 복사되므로 변경 가능하다.
하지만 List.of()는 불변 리스트이므로 요소 조작시 예외가 발생한다.

 

유지보수성이 더 중요하다면 컬렉션을 빈 상태로 생성 후 메서드를 사용해 직접 초기화 하는 방법이 좋을 수 있다.

728x90