给定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());
}
其他回答
另一种简单的方法是使用for each循环将数组中的所有元素添加到新的ArrayList中。
ArrayList<Element> list = new ArrayList<>();
for(Element e : array)
list.add(e);
使用以下代码将元素数组转换为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]);
}
另一种方式(虽然本质上等同于新的ArrayList(array.asList(array))解决方案的性能:
Collections.addAll(arraylist, array);
如果您使用:
new ArrayList<T>(Arrays.asList(myArray));
您可以创建并填写两个列表!在一个大列表中填充两次正是您不想做的,因为每次需要扩展容量时,它都会创建另一个Object[]数组。
幸运的是,JDK实现速度很快,Arrays.asList(a[])做得很好。它创建一种名为Arrays.ArrayList的ArrayList,其中Object[]数据直接指向数组。
// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>
private final E[] a;
ArrayList(E[] array) {
a = array; // you point to the previous array
}
....
}
危险的一面是,如果更改初始数组,则会更改列表!你确定你想要吗?也许是,也许不是。
如果不是,最容易理解的方法是这样做:
ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
list.add(element);
}
或者如@glglgl所述,您可以创建另一个独立的ArrayList:
new ArrayList<T>(Arrays.asList(myArray));
我喜欢使用集合、数组或番石榴。但如果它不合适,或者你感觉不到,就写另一行不雅的行。
鉴于:
Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
最简单的答案是:
List<Element> list = Arrays.asList(array);
这会很好的。但需要注意的是:
从asList返回的列表大小固定。因此,如果您希望能够在代码中添加或删除返回列表中的元素,则需要将其包装在新的ArrayList中。否则,您将获得UnsupportedOperationException。从asList()返回的列表由原始数组支持。如果修改原始数组,列表也将被修改。这可能令人惊讶。