Collections.unmodifiableList() vs List.of() vs List.copyOf() : 공통점과 차이점
불변 리스트를 만들기 위한 방법으로 어떤 것들이 있을까 하고 검색 해 보던 중, Collectors.unmodifiableList() 를 사용하는 방법과 List.of()를 사용하는 방법이 가장 많이 노출 되었다.
unmodifiableList()와 List.of()의 차이
정말 간단히 정리하자면 다음과 같다
unmodifiableList() |
List.of() |
|
추가 | Java 1.2 | Java 9 |
원본 | 복사x | 복사o |
사용 방법 | 목표컬렉션.stream().collect(Collectors.toUnmodifiableList()); | List.of(목표 요소, 목표 요소,...) |
공통점: 요소 변경 시 예외는 UnsupportedOperationException이며, 또한 둘 다 List, Map, Set으로 불변하게 만들어줄 수 있다.
ex) unmodifiableMap, unmodifiableSet, Map.of(), Set.of()
그렇다면 List.of()와 List.copyOf()의 차이점은 뭘까?
두 메서드 다 해당하는 요소를 불변 리스트로 만들어 주는 기능은 동일하지만, 파라미터로 받을 수 있는 값이 다르다.
List.of()는 개별 요소만 파라미터로 받을 수 있는 반면, List.copyOf()는 컬렉션을 인수로 사용할 수 있다는 차이가 있다.
ex) List.of(1, 2, 3) == List.copyOf(Arrays.asList(1, 2, 3))
또한 List.of()는 Java9에서 추가 된 반면, List.copyOf()는 Java10에서 추가되었다.
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
https://docs.oracle.com/javase/9/docs/api/java/util/List.html#of-E...-
List (Java SE 9 & JDK 9 )
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the lis
docs.oracle.com
https://docs.oracle.com/javase/10/docs/api/java/util/List.html#copyOf(java.util.Collection)
List (Java SE 10 & JDK 10 )
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the lis
docs.oracle.com
개인적인 생각을 정리한 내용이므로 잘못된 내용이 있을 수 있습니다. 발견 시 알려주시면 감사하겠습니다🙇🏻♀️