给定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);
其他回答
new ArrayList<>(Arrays.asList(array));
生成ArrayList<Element>类型列表的lambda表达式(1) 没有未检查的强制转换(2) 而不创建第二个列表(使用例如asList())
ArrayList<Element>list=Stream.of(array).collector(Collectors.toCollection(ArrayList::new));
使用Stream(从java 16开始)
new ArrayList<>(Arrays.stream(array).toList());
您也可以使用Java8中的流来实现这一点。
List<Element> elements = Arrays.stream(array).collect(Collectors.toList());
自从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());
}