给定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 = ???;
当前回答
自从Java 8以来,有一种更简单的转换方法:
import java.util.List;
import static java.util.stream.Collectors.toList;
public static <T> List<T> fromArray(T[] array) {
return Arrays.stream(array).collect(toList());
}
其他回答
使用以下代码
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) 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));
这应该是一种魅力。
根据这个问题,使用java 1.7的答案是:
ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));
但是,最好始终使用界面:
List<Element> arraylist = Arrays.<Element>asList(array);
给定对象数组:
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(array.asList(array))解决方案的性能:
Collections.addAll(arraylist, array);