给定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 = ???;
当前回答
下面的代码似乎是很好的方法。
new ArrayList<T>(Arrays.asList(myArray));
其他回答
您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:
List<Element> arraylist = Arrays.asList(array);
自从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());
}
由于这个问题很古老,所以我很惊讶,还没有人提出最简单的形式:
List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));
从Java5开始,Arrays.asList()采用varargs参数,不必显式构造数组。
还有一种方法可以用于将数组转换为ArrayList。您可以遍历数组并将每个索引插入ArrayList中,然后将其返回到ArrayList。
如下所示。
public static void main(String[] args) {
String[] array = {new String("David"), new String("John"), new String("Mike")};
ArrayList<String> theArrayList = convertToArrayList(array);
}
private static ArrayList<String> convertToArrayList(String[] array) {
ArrayList<String> convertedArray = new ArrayList<String>();
for (String element : array) {
convertedArray.add(element);
}
return convertedArray;
}
另一种简单的方法是使用for each循环将数组中的所有元素添加到新的ArrayList中。
ArrayList<Element> list = new ArrayList<>();
for(Element e : array)
list.add(e);