给定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 = ???;
当前回答
您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:
List<Element> 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<>(Arrays.asList(array));
new ArrayList<T>(Arrays.asList(myArray));
确保myArray的类型与T相同。例如,如果尝试从int数组创建List<Integer>,则会出现编译器错误。
生成ArrayList<Element>类型列表的lambda表达式(1) 没有未检查的强制转换(2) 而不创建第二个列表(使用例如asList())
ArrayList<Element>list=Stream.of(array).collector(Collectors.toCollection(ArrayList::new));
使用以下代码
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) Arrays.asList(array);