将数组转换为Java中的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2607289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:48:53  来源:igfitidea点击:

Converting array to list in Java

javaarrayslistdata-conversion

提问by Alexandru

How do I convert an array to a list in Java?

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

I used the Arrays.asList()but the behavior (and signature) somehow changed from Java SE 1.4.2(docs now in archive) to 8and most snippets I found on the web use the 1.4.2 behaviour.

我使用了Arrays.asList()但行为(和签名)不知何故从 Java SE 1.4.2(文档现在存档)更改为8,我在网上找到的大多数片段都使用 1.4.2 行为。

For example:

例如:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam)
  • on 1.4.2 returns a list containing the elements 1, 2, 3
  • on 1.5.0+ returns a list containing the array spam
  • 在 1.4.2 上返回一个包含元素 1、2、3 的列表
  • 在 1.5.0+ 上返回一个包含数组垃圾邮件的列表

In many cases it should be easy to detect, but sometimes it can slip unnoticed:

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

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

采纳答案by Joe Daley

In your example, it is because you can't have a List of a primitive type. In other words, List<int>is not possible.

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

You can, however, have a List<Integer>using the Integerclass that wraps the intprimitive. Convert your array to a Listwith the Arrays.asListutility method.

但是,您可以List<Integer>使用Integer包装int原语的类。List使用Arrays.asList实用方法将您的数组转换为 a 。

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

See this code run live at IdeOne.com.

查看此代码在 IdeOne.com 上实时运行

回答by Péter T?r?k

The problem is that varargs got introduced in Java5 and unfortunately, Arrays.asList()got overloaded with a vararg version too. So Arrays.asList(spam)is understood by the Java5 compiler as a vararg parameter of int arrays.

问题是可变参数是在 Java5 中引入的,不幸的是,可变参数Arrays.asList()版本也超载了。因此Arrays.asList(spam),Java5 编译器将其理解为 int 数组的 vararg 参数。

This problem is explained in more details in Effective Java 2nd Ed., Chapter 7, Item 42.

这个问题在 Effective Java 2nd Ed., Chapter 7, Item 42 中有更详细的解释。

回答by Giancarlo Frison

you have to cast in to array

你必须转换成数组

Arrays.asList((Object[]) array)

回答by Steve Gelman

I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.

我最近不得不将数组转换为列表。后来程序过滤了列表,试图删除数据。当您使用 Arrays.asList(array) 函数时,您创建了一个固定大小的集合:您既不能添加也不能删除。这篇文章比我能更好地解释这个问题:为什么在尝试从列表中删除元素时会得到 UnsupportedOperationException?.

In the end, I had to do a "manual" conversion:

最后,我不得不进行“手动”转换:

    List<ListItem> items = new ArrayList<ListItem>();
    for (ListItem item: itemsArray) {
        items.add(item);
    }

I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.

我想我可以使用 List.addAll(items) 操作添加从数组到列表的转换。

回答by Roman Nikitchenko

Speaking about conversion way, it depends on why do you need your List. If you need it just to read data. OK, here you go:

说到转换方式,这取决于你为什么需要你的List. 如果您只需要它来读取数据。好的,给你:

Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);

But then if you do something like this:

但是如果你做这样的事情:

list.add(1);

you get java.lang.UnsupportedOperationException. So for some cases you even need this:

你得到java.lang.UnsupportedOperationException。所以在某些情况下,你甚至需要这个:

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

First approach actually does not convert array but 'represents' it like a List. But array is under the hood with all its properties like fixed number of elements. Please note you need to specify type when constructing ArrayList.

第一种方法实际上不会转换数组,而是像List. 但是数组隐藏在其所有属性中,例如固定数量的元素。请注意,您需要在构建时指定类型ArrayList

回答by Ibrahim Arief

In Java 8, you can use streams:

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

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

回答by alaster

Another workaround if you use apache commons-lang:

如果您使用 apache commons-lang 的另一种解决方法:

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

Where ArrayUtils.toObjectconverts int[]to Integer[]

ArrayUtils.toObject转换int[]Integer[]

回答by akhil_mittal

It seems little late but here are my two cents. We cannot have List<int>as intis a primitive type so we can only have List<Integer>.

似乎有点晚了,但这是我的两分钱。我们不能List<int>因为int是基本类型,所以我们只能有List<Integer>

Java 8 (int array)

Java 8(整数数组)

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

Java 8 and below (Integer array)

Java 8 及以下(整数数组)

Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 =  Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only

Need ArrayList and not List?

需要 ArrayList 而不是 List?

In case we want a specific implementation of Liste.g. ArrayListthen we can use toCollectionas:

如果我们想要一个特定的Listeg实现,ArrayList那么我们可以使用toCollection

ArrayList<Integer> list24 = Arrays.stream(integers)
                          .collect(Collectors.toCollection(ArrayList::new));


Why list21cannot be structurally modified?

为什么list21不能在结构上进行修改?

When we use Arrays.asListthe size of the returned list is fixed because the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. So if we add or remove elements from the returned list, an UnsupportedOperationExceptionwill be thrown. So we should go with list22when we want to modify the list. If we have Java8 then we can also go with list23.

我们使用时Arrays.asList返回的列表的大小是固定的,因为返回的列表不是java.util.ArrayList,而是里面定义的一个私有静态类java.util.Arrays。因此,如果我们从返回的列表中添加或删除元素,UnsupportedOperationException将会抛出an 。所以list22当我们要修改列表时,我们应该使用。如果我们有 Java8,那么我们也可以使用list23.

To be clear list21can be modified in sense that we can call list21.set(index,element)but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this question.

明确list21地说,可以在我们可以调用的意义上进行修改,list21.set(index,element)但此列表可能不会在结构上进行修改,即无法从列表中添加或删除元素。你也可以检查这个问题



If we want an immutable list then we can wrap it as:

如果我们想要一个不可变的列表,那么我们可以将它包装为:

List<Integer> list 22 = Collections.unmodifiableList(Arrays.asList(integers));

Another point to note is that the method Collections.unmodifiableListreturns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.

另一点要注意的是,该方法Collections.unmodifiableList返回指定列表的不可修改视图。不可修改的视图集合是不可修改的集合,也是支持集合的视图。请注意,对后备集合的更改可能仍然是可能的,如果发生更改,它们将通过不可修改的视图可见。

We can have a truly immutable list in Java 9 and 10.

我们可以在 Java 9 和 10 中拥有一个真正不可变的列表。

Truly Immutable list

真正不可变的列表

Java 9:

爪哇 9:

String[] objects = {"Apple", "Ball", "Cat"};
List<String> objectList = List.of(objects);

Java 10 (Truly Immutable list) in two ways:

Java 10(真正不可变列表)有两种方式:

  1. List.copyOf(Arrays.asList(integers))
  2. Arrays.stream(integers).collect(Collectors.toUnmodifiableList());
  1. List.copyOf(Arrays.asList(integers))
  2. Arrays.stream(integers).collect(Collectors.toUnmodifiableList());

Also check this answerof mine for more.

另请查看我的这个答案以获取更多信息。

回答by Bhushan

One-liner:

单线:

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

回答by Vitaliy Sokolov

Even shorter:

更短:

List<Integer> list = Arrays.asList(1, 2, 3, 4);