给定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);
其他回答
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);
您也可以使用Java8中的流来实现这一点。
List<Element> elements = Arrays.stream(array).collect(Collectors.toList());
对于正常大小的数组,上面的答案是正确的。如果您有巨大的数组大小并使用java8,您可以使用流来实现。
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> list = Arrays.stream(array).collect(Collectors.toList());
最简单的方法是添加以下代码。经过测试。
String[] Array1={"one","two","three"};
ArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));
自从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());
}