20230402 [List.of vs Arrays.asList]

Daisy🌷·2023년 4월 2일
0

1. List.of는 불변 리스트를 반환하고 Arrays.asList는 가변 리스트를 반환한다.

List<Integer> list = Arrays.asList(1, 2, null);
list.set(1, 10); // OK
List<Integer> list = List.of(1, 2, 3);
list.set(1, 10); // Fails with UnsupportedOperationException

2. Arrays.asList는 null값을 허용하지만 List.of는 허용하지 않는다.

List<Integer> list = Arrays.asList(1, 2, null); // OK
List<Integer> list = List.of(1, 2, null); // Fails with NullPointerException

3. Arrays.asList는 배열에 대한 변경 사항이 반환되는 list에도 반영되지만 List.of의 경우 그렇지 않다.

Integer[] array = {1,2,3};
List<Integer> list = Arrays.asList(array);
array[1] = 10;
System.out.println(list); // Prints [1, 10, 3]
Integer[] array = {1,2,3};
List<Integer> list = List.of(array);
array[1] = 10;
System.out.println(list); // Prints [1, 2, 3]

+) 불변객체(immutable object)와 가변객체(mutable)

  • 객체 지향 프로그래밍에 있어서 불변객체(immutable object)는 생성 후 그 상태를 바꿀 수 없는 객체를 말한다.
  • 반대 개념으로는 가변(mutable) 객체로 생성 후에도 상태를 변경할 수 있다.
  • 불변 객체를 사용하면 복제나 비교를 위한 조작을 단순화 할 수 있고, 성능 개선에도 도움을 준다. 하지만 객체가 변경 가능한 데이터를 많이 가지고 있는 경우엔 불변이 오히려 부적절한 경우가 있다.

+) unmodifiableList를 반환하면 더 좋은 이유?

만약 객체가 변경 가능한 리스트를 반환하게 되면 원치 않는 내부 상태 변경에 노출되며, 이는 캡슐화의 원칙에 위배되기 때문이다.

profile
Frontend Developer

0개의 댓글