어제 오늘 내일

[Java 기초] Collections.unmodifiableList()로 읽기 전용 리스트 만들기 본문

IT/Java

[Java 기초] Collections.unmodifiableList()로 읽기 전용 리스트 만들기

hi.anna 2025. 9. 5. 01:45

리스트를 다른 메서드나 클래스에 전달할 때, 그 리스트가 변경되지 않도록 보호해야 할 때가 있습니다.
이럴 때 Collections.unmodifiableList()를 사용하면 안전하게 수정 불가능한 리스트를 만들 수 있습니다.
이 메서드는 리스트를 읽기 전용(수정 불가)으로 만들어 줍니다.

 

1. 기본 사용법

import java.util.*;

public class UnmodifiableListExample1 {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "orange"));

        List<String> readOnlyFruits = Collections.unmodifiableList(fruits);

        System.out.println(readOnlyFruits);
    }
}

실행 결과

[apple, banana, orange]

👉 출력은 정상적으로 되지만, 리스트 수정은 불가능합니다.

 

2. 수정 시도해보기

import java.util.*;

public class UnmodifiableListExample2 {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3));

        List<Integer> readOnlyNumbers = Collections.unmodifiableList(numbers);

        // 수정 시도
        readOnlyNumbers.add(4);
    }
}

실행 결과 (예외 발생)

Exception in thread "main" java.lang.UnsupportedOperationException

👉 읽기 전용 리스트에서 add(), remove(), set() 같은 메서드를 호출하면 UnsupportedOperationException이 발생합니다.

 

3. 원본 리스트는 여전히 수정 가능

unmodifiableList()원본 리스트를 감싼 뷰(View)를 반환합니다.
즉, 원본 리스트를 수정하면 읽기 전용 리스트도 바뀝니다.

import java.util.*;

public class UnmodifiableListExample3 {
    public static void main(String[] args) {
        List<String> animals = new ArrayList<>(Arrays.asList("dog", "cat"));

        List<String> readOnlyAnimals = Collections.unmodifiableList(animals);

        animals.add("bird"); // 원본 수정

        System.out.println(readOnlyAnimals);
    }
}

실행 결과

[dog, cat, bird]

👉 원본 리스트에 "bird"를 추가했더니 읽기 전용 리스트에도 반영되었습니다.

 

4. 활용 예시

  • 안전한 API 설계: 외부에 리스트를 넘겨줄 때 원본 데이터를 보호
  • 불변 객체 패턴 구현: 리스트가 바뀌면 안 되는 객체에 사용
  • 읽기 전용 뷰 제공: 특정 데이터는 조회만 가능하게 제한

 

5. 정리

  • Collections.unmodifiableList(List<T>)
    👉 수정 불가능한 읽기 전용 리스트를 반환
  • 수정 시도 → UnsupportedOperationException 발생
  • 원본 리스트는 여전히 수정 가능 (변경 사항이 뷰에도 반영됨)

👉 리스트를 외부에 안전하게 전달하려면 Collections.unmodifiableList()로 읽기 전용으로 만들어라!

 

 

반응형
Comments