给定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());
}
其他回答
嗨,你可以使用这行代码,这是最简单的方法
new ArrayList<>(Arrays.asList(myArray));
或者如果您使用Java 9,也可以使用以下方法:
List<String> list = List.of("Hello", "Java");
List<Integer> list = List.of(1, 2, 3);
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> list = List.of(array);
or
List<Element> list = Arrays.asList(array);
这两种方法都可以将其转换为列表。
new ArrayList<>(Arrays.asList(array));
还有一种方法可以用于将数组转换为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;
}
new ArrayList<T>(Arrays.asList(myArray));
确保myArray的类型与T相同。例如,如果尝试从int数组创建List<Integer>,则会出现编译器错误。