我有一个数组我想变成List
,以改变所述阵列的内容。
堆栈溢出有大量的问题/,解决Arrays.asList()
答案,以及如何它只提供了基本数组的列表视图,以及如何试图操纵结果列表通常会抛出一个UnsupportedOperationException
如用来操纵列表的方法(例如add()
,remove()
,等)不通过Arrays.asList()
提供的列表实现来实现。
但我不能找到如何把一个数组转换成一个可变的列表的例子。我想我可以通过阵列和put()
每个值到一个新的列表循环,但我不知道是否有存在为我做这一个接口。
一个简单的方法:
Foo[] array = ...;
List<Foo> list = new ArrayList<Foo>(Arrays.asList(array));
这将创建一个可变的名单 - 但是这将是原始数组的一个副本。更改列表不会改变阵列。您可以在以后将它复制回,当然,使用toArray
。
如果你想创建一个可变的视图到阵列上,我相信你必须实现一个自己。
如果你正在使用谷歌收集的API
Lists.newArrayList(myArray)
使用包括在爪哇8的流API这个简单的代码创建含有数组的元素一个可变的列表(或视图):
Foo[] array = ...;
List<Foo> list = Stream.of(array).collect(Collectors.toCollection(ArrayList::new));
或者,同样有效:
List<Foo> list = Arrays.stream(array).collect(Collectors.toCollection(ArrayList::new));
如果您使用Eclipse Collections(原GS Collections),你可以使用FastList.newListWith(...)
或FastList.wrapCopy(...)
。
这两种方法都采用可变参数,这样你就可以创建数组在线或通过现有阵列英寸
MutableList<Integer> list1 = FastList.newListWith(1, 2, 3, 4);
Integer[] array2 = {1, 2, 3, 4};
MutableList<Integer> list2 = FastList.newListWith(array2);
这两种方法之间的差异是所述阵列是否被复制。 newListWith()
不复制阵列,因此需要一定的时间。如果你知道数组可以在别处突变,你应该避免使用它。
Integer[] array2 = {1, 2, 3, 4};
MutableList<Integer> list2 = FastList.newListWith(array2);
array2[1] = 5;
Assert.assertEquals(FastList.newListWith(1, 5, 3, 4), list2);
Integer[] array3 = {1, 2, 3, 4};
MutableList<Integer> list3 = FastList.wrapCopy(array3);
array3[1] = 5;
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4), list3);
注:我的Eclipse集合的参与者。
myNewArrayList = new ArrayList<>(Arrays.asList(myArray));
添加使用流API的另一种选择:
List<Foo> list = Arrays.stream(array).collect(Collectors.toList());