给定Element[]类型的数组:

Element[] array = {new Element(1), new Element(2), new Element(3)};

如何将此数组转换为ArrayList<Element>类型的对象?

ArrayList<Element> arrayList = ???;

当前回答

Element[] array = {new Element(1), new Element(2), new Element(3)};

List<Element> list = List.of(array);

or

List<Element> list = Arrays.asList(array);

这两种方法都可以将其转换为列表。

其他回答

在调用Arrays接口时,还可以使用多态性声明ArrayList,如下所示:

List<Element>arraylist=newArrayList<Integer>(Arrays.asList(array));

例子:

Integer[] array = {1};    // autoboxing
List<Integer> arraylist = new ArrayList<Integer>(Arrays.asList(array));

这应该是一种魅力。

// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray); 

每个人已经为你的问题提供了足够好的答案。现在,从所有的建议中,你需要决定哪一个符合你的要求。您需要了解两种类型的集合。一个是未修改的集合,另一个是允许您稍后修改对象的集合。

因此,这里我将给出两个用例的简短示例。

不可变集合创建::创建后不想修改集合对象时List<Element>elementList=Arrays.asList(array)可变集合创建::创建后可能需要修改创建的集合对象时。List<Element>elementList=newArrayList<Element>(Arrays.asList(array));

在java中,主要有3种方法将数组转换为arrayList

使用Arrays.asList()方法:将所需的数组传递给此方法,并获取List对象,并将其作为参数传递给ArrayList类的构造函数。List<String>List=Arrays.asList(array);System.out.println(列表);Collections.addAll()方法-在使用此方法之前创建一个新列表,然后使用此方法将数组元素添加到现有列表中。List<String>list1=newArrayList<String>();Collections.addAll(列表1,数组);System.out.println(列表1);迭代方法-创建新列表。循环数组并将每个元素添加到列表中。List<String>list2=newArrayList<String>();for(字符串文本:数组){list2.add(文本);}System.out.println(列表2);

你也可以参考这个文档

使用以下代码

Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) Arrays.asList(array);