给定Element[]类型的数组:

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

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

ArrayList<Element> arrayList = ???;

当前回答

您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:

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

其他回答

使用以下代码

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

可以使用不同的方法进行转换

List<Element>List=Arrays.asList(array);List<Element>List=newArrayList();Collections.addAll(列表,数组);Arraylist列表=新Arraylist();list.addAll(Arrays.asList(array));

有关详细信息,请参阅http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html

使用以下代码将元素数组转换为ArrayList。

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

ArrayList<Element>elementArray=new ArrayList();
for(int i=0;i<array.length;i++) {
    elementArray.add(array[i]);
}

生成ArrayList<Element>类型列表的lambda表达式(1) 没有未检查的强制转换(2) 而不创建第二个列表(使用例如asList())

ArrayList<Element>list=Stream.of(array).collector(Collectors.toCollection(ArrayList::new));

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

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

例子:

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

这应该是一种魅力。