티스토리 뷰
728x90
반응형
Java에서 List.of와 Arrays.asList는 리스트를 생성하는 방법이지만 두 메서드의 차이점이 있다.
불변성
List.of: 생성된 리스트는 불변(immutable)하며, 요소를 추가, 제거 또는 변경할 수 없다.
add, remove, set 등의 메서드를 사용할 수 없다.
Arrays.asList: 생성된 리스트는 크기는 변경할 수 있지만, 요소를 추가하거나 제거하는 등의 변경 작업은 안된다.
set은 가능하고, 변경은 원본 배열에 반영된다.
List<String> listOf = List.of("A", "B", "C");
try {
listOf.add("D"); // UnsupportedOperationException 발생
} catch (UnsupportedOperationException e) {
System.out.println("Cannot add element to List.of");
}
List<String> asList = Arrays.asList("X", "Y", "Z");
try {
asList.add("W"); // UnsupportedOperationException 발생
} catch (UnsupportedOperationException e) {
System.out.println("Cannot add element to Arrays.asList");
}
Null 요소
List.of: 요소로 null을 허용하지 않는다.
Arrays.asList: 요소로 null을 허용한다.
try {
List<String> listOfNull = List.of("A", null, "C");
} catch (NullPointerException e) {
System.out.println("Fail to add null in list");
}
List<String> asListWithNull = Arrays.asList("X", null, "Y", "Z");
System.out.println(asListWithNull); //[X, null, Y, Z]
배열 변화의 동작
List.of: 원본 배열이 변경되어도 생성된 리스트에 영향을 주지 않는다. 리스트는 불변이기 때문
Arrays.asList: 원본 배열의 변경이 리스트에 영향을 미친다. (리스트를 변경하면 원본 배열이 변경)
이는 래퍼 리스트이므로 원본 배열과 리스트가 같은 메모리를 공유한다.
String[] array = {"One", "Two", "Three"};
List<String> asListFromArray = Arrays.asList(array);
List<String> listOfFromArray = List.of(array);
System.out.println("Original array: " + Arrays.toString(array)); //[One, Two, Three]
System.out.println("List from array: " + asListFromArray); //[One, Two, Three]
System.out.println("ListOf from array: " + listOfFromArray); //[One, Two, Three]
array[0] = "Zero";
System.out.println("Modified array: " + Arrays.toString(array)); //[Zero, Two, Three]
System.out.println("List after array modification: " + asListFromArray); //[Zero, Two, Three]
System.out.println("ListOf after array modification: " + listOfFromArray); //[One, Two, Three]
asListFromArray.set(0, "1");
System.out.println("Origin array: " + Arrays.toString(array)); //[1, Two, Three]
System.out.println("List after array: " + asListFromArray); //[1, Two, Three]
728x90
반응형
'Java' 카테고리의 다른 글
[Java] 마이크로벤치마킹 JMH (0) | 2024.02.17 |
---|---|
[Java] JVM (0) | 2024.02.17 |
[Java] CPU 와 ThreadPool Size 결정 방법 (0) | 2024.01.29 |
[Java] Enum Singleton Pattern (0) | 2023.12.27 |
[Java] 기본적인 리팩터링 (0) | 2023.12.16 |
반응형
300x250