반응형
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- HashMap
- 자바스크립트
- js
- 정규식
- string
- CMD
- javascript
- json
- 배열
- 이탈리아
- vscode
- Visual Studio Code
- html
- map
- table
- 인텔리제이
- Button
- ArrayList
- 문자열
- 이클립스
- date
- list
- IntelliJ
- CSS
- 자바
- replace
- Array
- Java
- Eclipse
- input
Archives
- Today
- Total
어제 오늘 내일
[Java 기초] Collections.unmodifiableList()로 읽기 전용 리스트 만들기 본문
리스트를 다른 메서드나 클래스에 전달할 때, 그 리스트가 변경되지 않도록 보호해야 할 때가 있습니다.
이럴 때 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()로 읽기 전용으로 만들어라!
반응형
'IT > Java' 카테고리의 다른 글
| [Java 기초] Collections.emptyList()로 비어있는 불변 리스트 만들기 (0) | 2025.09.06 |
|---|---|
| [Java 기초] Collections.singletonList()로 단일 요소 불변 리스트 만들기 (0) | 2025.09.05 |
| [Java 기초] Collections.replaceAll()으로 리스트 요소 일괄 교체하기 (1) | 2025.09.04 |
| [Java 기초] Collections.swap()으로 리스트 요소 교환하기 (0) | 2025.09.04 |
| [Java 기초] Collections.max(), Collections.min()으로 최대/최소값 찾기 (0) | 2025.09.03 |
Comments