给定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 = ???;
当前回答
另一种方式(虽然本质上等同于新的ArrayList(array.asList(array))解决方案的性能:
Collections.addAll(arraylist, 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;
}
使用以下代码将元素数组转换为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]);
}
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> list = List.of(array);
or
List<Element> list = Arrays.asList(array);
这两种方法都可以将其转换为列表。
根据这个问题,使用java 1.7的答案是:
ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));
但是,最好始终使用界面:
List<Element> arraylist = Arrays.<Element>asList(array);
在Java 9中,您可以使用:
List<String> list = List.of("Hello", "World", "from", "Java");
List<Integer> list = List.of(1, 2, 3, 4, 5);