Java : Difference of Arrays.asList() & List.of()
I just want to record the difference between Arrays.asList() and List.of(), as they are used in one of my technical interviews.
The purpose is simple : creating a List and manipulating it with stream (nowadays it's much faster to write a collection with stream), and these two methods were taken into consideration then.
Arrays.asList() and List.of() are both methods for creating a List object. Both methods can use get(int index), but not add(T obj) and remove(int index), the main differences are :
- Arrays.asList()
- We can use
set(int, T obj) - API introduced in Java 1.2
- We can use
- List.of()
- We can't use
set(int, T obj) - API introduced in Java 9
- We can't use
That is, Arrays.asList() can modify values, and List.of() values are read-only, then consider the following reasons that I used to solve the problem.
- Creating a new stream instead of modifying the original List
I decided to use List.of() instead of Arrays.asList().
code reference
List<String> orgin = List.of("1", "2", "3");
List<String> modify = orgin.stream()
.map(s -> "TEST-" + s)
.collect(Collectors.toList());
System.out.println(modify);
// [TEST-1, TEST-2, TEST-3]這篇簡單紀錄一下 Arrays.asList() 與 List.of() 的差異,因為面試有用到。
使用情境滿單純的,就是建立一個 List 然後用 stream 去操縱它們 (現在用 stream 寫 collection 會快很多,滿多公司都有考用法),那時候就有考慮到這兩個方法。
Arrays.asList() 與 List.of() 這兩個都是建立 List object 的方法,這兩個方法都能用 get(int index),但不能用 add(T obj) 和 remove(int index),比較主要的差異為
- Arrays.asList()
- 可以用
set(int, T obj) - Java 1.2 推出的 API
- 可以用
- List.of()
- 不能用
set(int, T obj) - Java 9 之後才有
- 不能用
也就是說,Arrays.asList() 可以修改值,List.of() 的值是唯讀的,那時候考量
- 我需要建立一個新的 stream 輸出,而不是修改原始的 List
所以使用 List.of() 而不是 Arrays.asList()
大概是這樣子,code 可以參考上面囉。