使用Arrays.asList()创建列表的好处 [英] Benefits of creating a List using Arrays.asList()

查看:318
本文介绍了使用Arrays.asList()创建列表的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅 Arrays.asList(array)与新ArrayList之间的差异; java中的Integer>(Arrays.asList(ia)) 我很好奇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

公共静态列表asList(T ... a)

public static List asList(T... a)

返回由指定数组支持的固定大小的列表. (更改为 返回的列表直写"到数组.)此方法用作 结合使用基于数组的API和基于集合的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<Integer> list3 = new ArrayList<>(Arrays.asList(I));

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?

推荐答案

不能调用添加,删除等是确切的区别.如果不需要这些方法,则Arrays.asList可以为列表提供一个完美的数组视图(对于采用集合而不是数组的API).如果需要更改列表的形状",则可以使用新的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆