Java/문제 해결 (Troubleshooting)

List.of()로 만든 리스트에서 add()가 안 되는 이유

가지코딩 2025. 4. 30. 15:08

문제 상황 (예시)

List.of() 로 초기화 한 리스트에 값을 추가할 수 없는 문제

List<String> items = List.of("apple", "banana");
items.add("cherry"); // 예외 발생

 

java.lang.UnsupportedOperationException


문제 원인

List.of(...)는 Java 9부터 제공되는 불변 리스트 (Immutable List) 를 생성하는 정적 팩토리 메서드이다.

  • 불변(immutable): 값을 추가하거나 제거할 수 없다.
  • null 불허: List.of("a", null)처럼 null이 포함되면 NullPointerException 발생
  • 수정 불가: add(), remove(), set() 등 변경 연산은 모두 UnsupportedOperationException 발생

List.of(...)는 값을 안전하게 고정하고자 할 때 사용하는 리스트이다.


해결 방법

가변 리스트 생성하기 ~ !

 

List.of(...) 결과를 ArrayList로 감싸서 가변 리스트로 변환하면 된다.

List<String> items = new ArrayList<>(List.of("apple", "banana"));
items.add("cherry"); // OK

 

또는 생성자 사용하기

List<String> items = new ArrayList<>();
items.add("apple");
items.add("banana");
List<String> items = new ArrayList<>(){{
	add("apple");
    add("banana");
}};

 

 

 

배열 기반 리스트 (Arrays.asList) 는 값 변경은 가능하나, 크기 변경은 불가하니 주의

List<String> items = Arrays.asList("apple", "banana");
items.set(0, "orange"); // 가능
items.add("cherry");    // ❌ UnsupportedOperationException (크기 변경 불가)