给定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 = ???;
当前回答
对于正常大小的数组,上面的答案是正确的。如果您有巨大的数组大小并使用java8,您可以使用流来实现。
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> list = Arrays.stream(array).collect(Collectors.toList());
其他回答
Java 9
在Java9中,可以使用List.of静态工厂方法来创建List文本。类似以下内容:
List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));
这将返回一个包含三个元素的不可变列表。如果需要可变列表,请将该列表传递给ArrayList构造函数:
new ArrayList<>(List.of(// elements vararg))
JEP 269:便利工厂收集方法
JEP269为Java集合API提供了一些方便的工厂方法。这些不可变的静态工厂方法内置在Java9和更高版本的List、Set和Map接口中。
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);
可以使用不同的方法进行转换
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
给定对象数组:
Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};
将数组转换为列表:
List<Element> list = Arrays.stream(array).collect(Collectors.toList());
将数组转换为ArrayList
ArrayList<Element> arrayList = Arrays.stream(array)
.collect(Collectors.toCollection(ArrayList::new));
将数组转换为LinkedList
LinkedList<Element> linkedList = Arrays.stream(array)
.collect(Collectors.toCollection(LinkedList::new));
打印列表:
list.forEach(element -> {
System.out.println(element.i);
});
输出,输出
1
2
3
使用以下代码将元素数组转换为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]);
}