给定Element[]类型的数组:
Element[] array = {new Element(1), new Element(2), new Element(3)};
如何将此数组转换为ArrayList<Element>类型的对象?
ArrayList<Element> arrayList = ???;
给定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)};
ArrayList<Element> list = (ArrayList) 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[] { new Element(1), new Element(2), new Element(3) };
最简单的答案是:
List<Element> list = Arrays.asList(array);
这会很好的。但需要注意的是:
从asList返回的列表大小固定。因此,如果您希望能够在代码中添加或删除返回列表中的元素,则需要将其包装在新的ArrayList中。否则,您将获得UnsupportedOperationException。从asList()返回的列表由原始数组支持。如果修改原始数组,列表也将被修改。这可能令人惊讶。
您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:
List<Element> arraylist = Arrays.asList(array);
另一个Java8解决方案(我可能错过了大量的答案。如果是,我很抱歉)。这将创建一个ArrayList(与List相反),即可以删除元素
package package org.something.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Junk {
static <T> ArrayList<T> arrToArrayList(T[] arr){
return Arrays.asList(arr)
.stream()
.collect(Collectors.toCollection(ArrayList::new));
}
public static void main(String[] args) {
String[] sArr = new String[]{"Hello", "cruel", "world"};
List<String> ret = arrToArrayList(sArr);
// Verify one can remove an item and print list to verify so
ret.remove(1);
ret.stream()
.forEach(System.out::println);
}
}
输出是。。。你好世界
每个人已经为你的问题提供了足够好的答案。现在,从所有的建议中,你需要决定哪一个符合你的要求。您需要了解两种类型的集合。一个是未修改的集合,另一个是允许您稍后修改对象的集合。
因此,这里我将给出两个用例的简短示例。
不可变集合创建::创建后不想修改集合对象时List<Element>elementList=Arrays.asList(array)可变集合创建::创建后可能需要修改创建的集合对象时。List<Element>elementList=newArrayList<Element>(Arrays.asList(array));