List<Integer> list = List.of(4, 5, 1, 3, 2 ,6);
Collections.sort(list);
위 코드를 실행하면 UnsupportedOperationException 를 마주한다. 왜그럴까?
결론부터 말하자면 list는 불변인 값인데 Collections.sort()를 통해 값을 바꾸려해서 나타나는 Exception이다.
이 글은 Java 17을 기준으로 작성하였습니다.
Exception이 발생한 위 코드를 디버깅해보면 아래 코드로 넘어간다.
static abstract class AbstractImmutableList<E> extends AbstractImmutableCollection<E>
implements List<E>, RandomAccess {
// all mutating methods throw UnsupportedOperationException
@Override public void add(int index, E element) { throw uoe(); }
@Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); }
@Override public E remove(int index) { throw uoe(); }
@Override public void replaceAll(UnaryOperator<E> operator) { throw uoe(); }
@Override public E set(int index, E element) { throw uoe(); }
@Override public void sort(Comparator<? super E> c) { throw uoe(); }
불변 리스트에서 추가, 수정, 삭제 등 리스트에 변화를 주는 메서드를 사용하게 되면 모두 UnsupportedOperationException이 발생하도록 예외처리를 한것 같다. 그리고 List.of()로 만든 List가 불변 리스트를 만드는 방법 중 하나인 것 같다.
이 외에도 아래와 같이 다른 방법을 통해 불변 리스트를 만들 수도 있다.
List<Integer> immutableList = Collections.unmodifiableList(new ArrayList<>());