2

这两种初始化方式有什么区别:

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

List<String> list = Arrays.asList(arr);

我可以弄清楚的一件事是,在后一种情况下,我们没有使用ArrayList该类。但是,我们在这里创建的是哪个类的对象(列表)?

4

4 回答 4

8

第一个创建一个 mutable List,第二个是固定大小的。ArrayList不是唯一的实现ListArrays.asList返回它自己的固定大小的实现,即可以更新单个元素但不能添加或删除元素。

于 2013-05-09T16:23:44.127 回答
2

我看到的唯一区别是这一秒将创建一个不可变List对象。

于 2013-05-09T16:23:00.060 回答
1

In List<String> list = Arrays.asList(arr);

Arrays.asList(arr) return a fixed-size list backed by the arr array of String type. It doesn’t implement the add or remove method (as it says in the specs is fixed size list).

So if you are trying to add something like these

list.add("StackOverflow")

You will be getting an UnsupportedOperationException (Thrown to indicate that the requested operation is not supported.) because the returned list is of fix size.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/UnsupportedOperationException.html

In List<String> list = new ArrayList<String>(Arrays.asList(arr));

new ArrayList<String>(Arrays.asList(arr)) returns a list containing the elements of the fixed-size list backed by the arr array of String type, in the order they are returned by the collection's iterator.

So here if you are trying to add something like these

list.add("StackOverflow")

Then it will be getting added that's the difference.

于 2013-05-09T16:33:32.210 回答
0

对于第一个,您将列表arr传递给返回列表的静态方法asList,然后使用该方法的结果作为构造函数参数创建一个新的 ArrayList。

对于第二个,您直接使用静态方法的结果作为对象。

于 2013-05-09T16:25:02.963 回答