目录
Arrays.asList()方法的官方文档介绍:
Modifier and Type | Method and Description |
---|---|
static <T> List<T> | asList(T... a) Returns a fixed-size list backed by the specified array. |
-
asList
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@SafeVarargs public static <T> List<T> asList(T... a)
Collection.toArray()
. The returned list is serializable and implementsRandomAccess
.This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
Type Parameters:
T
- the class of the objects in the arrayParameters:
a
- the array by which the list will be backedReturns:
a list view of the specified array
官方文档介绍的个人总结
1、返回一个固定大小的list,为什么说是固定大小的?因为这个返回的list不支持add()、remove()、clear()等会修改list集合元素个数的方法(原因见通过Arrays.asList方法将数组转成集合后,能否修改集合个数? (juejin.cn))
2、既然返回的list不能修改元素个数,那么这个返回的list主要是起什么作用的?
This method acts as bridge between array-based and collection-based APIs
有些API是基于数组操作的,有些API是基于集合操作的,这个方法主要是为了将数组转化成集合以方便使用一些基于集合操作的API
同理,Collection.toArray()
也是起到一个类似的作用,将集合转化为数组以方便使用一些基于数组操作的API
例子如下,翻转操作只存在于Collections类的方法中,为了反转words数组我们使用Arrays.asList将其转换为List集合
Collections.reverse(Arrays.asList(words));
对返回List的修改会同步修改原数组,反之亦然
对原数组修改会同步修改返回List
如果我们在使用asList的时候,对原始数组进行修改,那么会出现什么结果?
public static void main(String[] args) {
String[] arr1 = {"1","2","3","4","5"};
List list2 = Arrays.asList(arr1);
System.out.println(list2);
arr1[1] = "0";
System.out.println(list2);
}
输出为:
[1, 2, 3, 4, 5]
[1, 0, 3, 4, 5]
可以看到,当我们使用asList之后,再对其原始的数组进行修改,那么之前被转换的List的值也会发生变化。如果我们把这个结果通过参数传递给其他线程,那么可能就会产生很多共享数据导致的奇怪问题。
对返回List修改会同步修改原数组
通过Arrays.asList方法将数组转成集合后,能否修改集合个数?针对这个问题,我们直接给出例子:
public class Demo {
public static void main(String[] args){
String[] strings={"A","B","C"};
List<String> stringList=Arrays.asList(strings);
stringList.set(0,"G");
System.out.println(strings[0]);
stringList.add("M");
}
}
复制代码
运行结果:
G
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
...
原因(和内部实现Arrays有关)
通过Arrays.asList方法将数组转成集合后,能否修改集合个数? (juejin.cn)