给定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 = ???;
当前回答
另一种简单的方法是使用for each循环将数组中的所有元素添加到新的ArrayList中。
ArrayList<Element> list = new ArrayList<>();
for(Element e : array)
list.add(e);
其他回答
new ArrayList<T>(Arrays.asList(myArray));
确保myArray的类型与T相同。例如,如果尝试从int数组创建List<Integer>,则会出现编译器错误。
尽管这个问题有很多完美的书面答案,我还是会补充我的意见。
假设你有Element〔〕array={new Element(1),new Element(2),new Element(3)};
可以通过以下方式创建新的ArrayList
ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));
ArrayList<Element> arraylist_2 = new ArrayList<>(
Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));
// Add through a collection
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);
它们非常支持ArrayList的所有操作
arraylist_1.add(new Element(4)); // or remove(): Success
arraylist_2.add(new Element(4)); // or remove(): Success
arraylist_3.add(new Element(4)); // or remove(): Success
但以下操作只返回ArrayList的List视图,而不是实际的ArrayList。
// Returns a List view of array and not actual ArrayList
List<Element> listView_1 = (List<Element>) Arrays.asList(array);
List<Element> listView_2 = Arrays.asList(array);
List<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));
因此,当尝试执行某些ArrayList操作时,它们会给出错误
listView_1.add(new Element(4)); // Error
listView_2.add(new Element(4)); // Error
listView_3.add(new Element(4)); // Error
有关数组链接的列表表示的详细信息。
还有一种方法可以用于将数组转换为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;
}
另一个Java8解决方案(我可能错过了大量的答案。如果是,我很抱歉)。这将创建一个ArrayList(与List相反),即可以删除元素
package package org.something.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Junk {
static <T> ArrayList<T> arrToArrayList(T[] arr){
return Arrays.asList(arr)
.stream()
.collect(Collectors.toCollection(ArrayList::new));
}
public static void main(String[] args) {
String[] sArr = new String[]{"Hello", "cruel", "world"};
List<String> ret = arrToArrayList(sArr);
// Verify one can remove an item and print list to verify so
ret.remove(1);
ret.stream()
.forEach(System.out::println);
}
}
输出是。。。你好世界
嗨,你可以使用这行代码,这是最简单的方法
new ArrayList<>(Arrays.asList(myArray));
或者如果您使用Java 9,也可以使用以下方法:
List<String> list = List.of("Hello", "Java");
List<Integer> list = List.of(1, 2, 3);