Java/Java

Java - Collections unmodifiable

Dlise 2023. 9. 19. 15:57

Java를 활용해 이것저것 만들다가 우연히 Collections 클래스의 unmodifiable 메서드를 알게 되었다.

자주 활용할 것 같아 간단히 정리하고자 한다.

 

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html

 

Collections (Java Platform SE 8 )

Rotates the elements in the specified list by the specified distance. After calling this method, the element at index i will be the element previously at index (i - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. (Thi

docs.oracle.com

 

Unmodifiable

Oracle 문서의 Collections 클래스를 확인해 보면 아래와 같이 각 자료구조에 따른 unmodifiable 메서드가 정의되어 있다.

설명을 보면 수정할 수 없는 보기를 반환한다고 설명이 나와있다.
리스트를 활용할 때 데이터 추가, 삭제를 막기 위해 활용하는 메서드이다.

 

unmodifiableList를 살펴보았다.

수정할 수 없는 read-only를 반환한다고 설명되어 있다.

만약 수정을 하려고 하면 "UnsupportedOperationException" 예외를 발생시킨다.

 

이를 활용해 보자.

Integer 리스트에 0 ~ 9까지 넣은 후 unmodifiableList를 활용한 코드이다.

import java.util.*;

public class unmodifiable {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        
        for(int i = 0; i < 10; i++) 
            list.add(i);

        useList(Collections.unmodifiableList(list));
    }

    public static void useList(List<Integer> list) {
        System.out.println(list.toString());
        list.remove(0);
    }
}

아래는 실행 결과이다.

 

설명에 나와있던 대로 UnsupportedOperationException 예외가 발생했다.

 

다만 읽기는 가능하기에 다른 리스트에 값을 옮긴 후 활용은 가능하다.

import java.util.*;

public class unmodifiable {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        
        for(int i = 0; i < 10; i++) 
            list.add(i);

        useList(Collections.unmodifiableList(list));
    }

    public static void useList(List<Integer> list) {
        List<Integer> newList = new ArrayList<>(list);
        newList.remove(0);

        System.out.println(newList.toString());
    }
}

출력 결과 0이 사라진 모습이다.

 

이렇게 활용하면 기존의 정보가 보존된다는 장점이 있다.