본문 바로가기
Language/Java

자바 Array.asList List.of 차이 정리

by wakestand 2022. 4. 26.
반응형

자바에서 Array.asList()와 List.of()의 주요 차이점은

Array.asList는 가변(mutable)이고

List.of는 불변(immutable) 이라는 것인데

 

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

 

Arrays.asList와 List.of를 사용해 List를 만든 후

set을 사용하면 Arrays.asList는 가변이기 때문에

에러가 나지 않지만

 

List.of의 경우에는

UnsupportedOperationException이 발생한다

 

다음으로 Array.asList에는 null을 할당할 수 있지만

List.of 에는 null을 할당할 수 없는데

 

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

 

List.of에 null을 할당하면

NullPointerException이 발생하는 것이 보인다

contain(null) 등을 사용해도 할당할 수 없기 때문에

동일한 Exception이 발생한다

 

정리를 해 보자면

NULL이 들어가거나 가변인 List를 만들 경우에는

Arrays.asList를 사용하고

 

NULL이 들어가면 안되고 불변인 List를 만들 경우에는

List.of를 사용해주면 된다

반응형

댓글