[Java] List.of VS Arrays.asList VS Collections.unmodifiableList

Loopy·2022년 10월 30일
1
post-thumbnail

Arrays.asList

  • modifiable 리스트이다. 따라서 리스트를 변경 가능하다.
    • 내부적으로 ArrayList 객체를 생성하기 때문이다.
    • 하지만 값을 추가하거나 삭제는 불가능하다.
asList.set(1, "a");  // modified unmodif! unmodif is not truly unmodifiable
  • null 값을 허용한다.
asList.contains(null);  // allowed

List.of

  • unmodifiable, 즉 불변 리스트이다. 따라서 리스트를 변경하고자 하면 예외를 발생시킨다.
listOf.set(1, "a");  // UnsupportedOperationException
  • null 값을 넣는 것은 물론 찾는 것도 허용하지 않으며, NullPointerException 을 발생시킨다.
listOf.contains(null);  // NullPointerException

Collections.unmodifiableList

  • unmodifiable, 마찬가지로 불변 리스트이며 읽기 전용 리스트를 반환한다.
    • 하지만 Collections.unmodifiableList()로 반환되는 List로는 직접적인 수정은 불가하지만, 참조하고 있는 List에 의한 수정은 막을 수 없다.
unmodif.set(1, "a"); // UnsupportedOperationException
  • null 값을 허용한다.
unmodif.contains(null); // allowed

참고자료
== three different list ==
https://stackoverflow.com/questions/46579074/what-is-the-difference-between-list-of-and-arrays-aslist
https://1minute-before6pm.tistory.com/1
==random access VS sequential access==
https://stackoverflow.com/questions/51177527/what-basically-is-randomaccess-why-we-use-randomaccess

profile
개인용으로 공부하는 공간입니다. 피드백 환영합니다 🙂

2개의 댓글

comment-user-thumbnail
2022년 10월 30일

잘 읽었습니다~ 저희 꾸준히 소통해요~

1개의 답글