使用 Arrays.asList() 创建列表的好处 [英] Benefits of creating a List using Arrays.asList()
问题描述
参考Arrays.asList(array) vs new ArrayList的区别<Integer>(Arrays.asList(ia)) in java我很好奇 Arrays.asList()
方法的确切目的是什么.
Referring to Difference between Arrays.asList(array) vs new ArrayList<Integer>(Arrays.asList(ia)) in java
I was curious as in what's the exact purpose of Arrays.asList()
method.
当我们从它创建一个新的 List
时,比如说 -
When we create a new List
from it, say for example -
Integer[] I = new Integer[] { new Integer(1), new Integer(2), new Integer(3) };
List<Integer> list1 = Arrays.asList(I);
List<Integer> list2 = ((List<Integer>) Arrays.asList(I));
我们无法对其执行大多数常规操作,例如 .add()
、.remove()
.因此,我无法向其添加迭代器以避免并发修改.
We cannot perform most of the the regular operations on it like .add()
, .remove()
. Thus, I was not able add an iterator to it to avoid concurrent modification.
Oracle 文档状态
Oracle docs state
public static List asList(T... a)
public static List asList(T... a)
返回由指定数组支持的固定大小列表.(更改为返回的列表直写"到数组中.)此方法充当结合基于数组和基于集合的 API 之间的桥梁使用 Collection.toArray().返回的列表是可序列化的,并且实现 RandomAccess.
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
它适用于创建一个新的List
.List
It works well with creating a new List
. List<Integer> list3 = new ArrayList<>(Arrays.asList(I));
那么,为什么会这样?它的优点和缺点是什么?
So, why this and what are its advantages and disadvantages?
推荐答案
不能调用 add、remove 等是完全不同的.如果您不需要这些方法,Arrays.asList 为您提供了一个完美的数组视图作为列表(对于采用集合而不是数组的 API).如果您需要更改列表的形状",那么 new ArrayList<>(Arrays.asList(myArray)) 是您要走的路.
Not being able to call add, remove, etc is the exact difference. If you don't need those methods, Arrays.asList gives you a perfectly fine view of the array as a List (for APIs that take collections rather than arrays). If you need to change the "shape" of the list, then new ArrayList<>(Arrays.asList(myArray)) is the way to go.
这篇关于使用 Arrays.asList() 创建列表的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!