如何在Java中将数组转换为列表?

我使用了Arrays.asList(),但行为(和签名)不知怎么地从Java SE 1.4.2(文档现在存档)改变到8,我在web上找到的大多数代码片段都使用1.4.2行为。

例如:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers)

在1.4.2返回一个包含元素1,2,3的列表 在1.5.0+上返回包含数组'numbers'的列表

在许多情况下,它应该很容易被发现,但有时它会被忽视:

Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);

当前回答

使用番石榴: Integer[] array = {1,2,3}; List<Integer> List = Lists.newArrayList(sourceArray); 使用Apache Commons Collections: Integer[] array = {1,2,3}; List<Integer> List = new ArrayList<>(6); CollectionUtils。addAll(列表、数组);

其他回答

在Java 9中,您可以通过新的方便的工厂方法List.of使用更优雅的不可变列表:

List<String> immutableList = List.of("one","two","three");

(无耻地从这里抄袭)

你必须转换为数组

Arrays.asList((Object[]) array)

你能不能改进这个答案,因为这是我使用的,但我不是100%清楚。它工作正常,但intelliJ增加了新的气象站[0]。为什么是0 ?

公共气象站[]removeElementAtIndex(气象站[]数组,int索引) { List<WeatherStation> List = new ArrayList<WeatherStation>(Arrays.asList(array)); list.remove(指数); 返回列表。toArray(新WeatherStation [0]); }

一行程序:

List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});

Int是一个原语。原语不能接受空值,只能有默认值。因此,要接受null,您需要使用包装器类Integer。

选项1:

int[] nos = { 1, 2, 3, 4, 5 };
Integer[] nosWrapped = Arrays.stream(nos).boxed()   
                                        .toArray(Integer[]::new);
nosWrapped[5] = null // can store null

选项2: 您可以使用任何使用包装器类Integer的数据结构

int[] nos = { 1, 2, 3, 4, 5 };
List<Integer> = Arrays.asList(nos)