如何在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);

当前回答

在Java 8中,你可以使用流:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.stream(numbers)
      .boxed()
      .collect(Collectors.toList());

其他回答

如果你使用Apache common -lang,另一个解决方法是:

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

ArrayUtils的地方。toObject将int[]转换为Integer[]

你必须转换为数组

Arrays.asList((Object[]) array)

在您的示例中,这是因为您不能拥有原始类型的List。换句话说,List<int>是不可能的。

但是,您可以使用包装int原语的Integer类来拥有一个List<Integer>。使用数组将数组转换为List。asList实用程序方法。

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

请在IdeOne.com上查看实时运行的代码。

因此,这取决于您正在尝试的Java版本

Java 7

 Arrays.asList(1, 2, 3);

OR

       final String arr[] = new String[] { "G", "E", "E", "K" };
       final List<String> initialList = new ArrayList<String>() {{
           add("C");
           add("O");
           add("D");
           add("I");
           add("N");
       }};

       // Elements of the array are appended at the end
       Collections.addAll(initialList, arr);

OR

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

在Java 8中

int[] num = new int[] {1, 2, 3};
List<Integer> list = Arrays.stream(num)
                        .boxed().collect(Collectors.<Integer>toList())

参考资料- http://www.codingeek.com/java/how-to-convert-array-to-list-in-java/

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)