Language/Java

[JAVA] List.of() vs Arrays.asList() 차이점

jungwon3004 2022. 1. 20. 13:48
728x90
반응형

0. 서론

List<String> l1 = new ArrayList<>();
List<String> l2 = Arrays.asList("일", "이", "삼");
List<String> l3 = List.of("하나", "둘", "셋");

이런 식의 코드들을 어디선가 본 적있을 수도 있다.

 

보통 우리가 List를 선언한다고 하면

List<String> l1 = new ArrayList<>(); // new LinkedList<>();

이런 식으로 new를 이용해서 새로운 객체를 생성한다.

 

하지만 가끔 코드들을 보다보면

Arrays.asList()와 List.of() 같은 method 통해서 List를 선언하는 코드들이 등장한다. 

 

이걸 하나씩 살펴보도록 하자.

 

728x90

 

1. List.of()

우선 orcale의 설명을 보자.

 

List.of()

<String> List<E> java.util.List.of(E e1, E e2, E e3 ...)

Type Paremeters: E

Paramenters: e1 e2 e3 ...

Returns: a List containing the specified elements (Returns an unmodifiable list containing elements.)

Throws: NullPointerException

Since: 9

 

결국

List<E> list = List.of(e1, e2, e3, e4, e5 ...);

이렇게 선언될 수 있다는 말이다.

 

하지만 단순히 여기서 그치면 안 된다.

 

위 설명에서 중요한 부분이 있다.

Returns an unmodifiable list containing elements.

바로 이 문장이다.

unmodifiable list를 return한다고 하다. 

즉, List.of()로 return된 list는 수정이 안 된다!

add(), set(), remove() 와 같은 수정이 안 된다.

딱 List.of(...) 로 생성된 그 list만 가질 수 있고 변화가 불가능하다는 것이다.

 

정리해보면, 우리가 보통 사용하는 java.util.ArrayList나 java.util.LinkedList와는 다른 새로운 List 타입인 것이다.

 

1. 수정 불가능

2. elements로 null value 불가능

 

반응형

2. Arrays.asList()

Arrays.asList()

public static <T> List<T> asList(T... a)

Type Paremeters: T

Paramenters: a - the array by which the list will be backed

Returns: a list view of the specified array (Return fixed-size list backed by the specified array.) (The returned list is serializable and implements RandomAccess.)

+ This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray.

 

이 설명을 보면 바로 이해가 될 것이다.

 

애초에 Arrays.asList() 의 존재 목적은 array와  Collection을 연결하기 위함이다.

array -> Collection : Arrays.asList()

Collection -> array : Collection.asArray()

// ArrayList<String> al => String[] arr

String[] arr = al.toArray(new String[al.size()]);
// String[] arr => ArrayList<String> al

ArrayList<String> al = new ArrayList<>(Arrays.asList(arr));

 

여기서 위 설명을 한 번 다시 읽어보자.

Return fixed-size list backed by the specified array

Arrays.asList(arr) 을 통해 만들어진 list의 크기는 고정되어있고 불변이다.

 

1. list 크기 고정

2. elements로 null value 가능

 

728x90
반응형