给定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中,主要有3种方法将数组转换为arrayList
使用Arrays.asList()方法:将所需的数组传递给此方法,并获取List对象,并将其作为参数传递给ArrayList类的构造函数。List<String>List=Arrays.asList(array);System.out.println(列表);Collections.addAll()方法-在使用此方法之前创建一个新列表,然后使用此方法将数组元素添加到现有列表中。List<String>list1=newArrayList<String>();Collections.addAll(列表1,数组);System.out.println(列表1);迭代方法-创建新列表。循环数组并将每个元素添加到列表中。List<String>list2=newArrayList<String>();for(字符串文本:数组){list2.add(文本);}System.out.println(列表2);
你也可以参考这个文档
其他回答
另一个更新,即将于2014年结束,您也可以使用Java 8完成:
ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));
如果这只是一个列表,则会保存几个字符
List<Element> list = Stream.of(myArray).collect(Collectors.toList());
生成ArrayList<Element>类型列表的lambda表达式(1) 没有未检查的强制转换(2) 而不创建第二个列表(使用例如asList())
ArrayList<Element>list=Stream.of(array).collector(Collectors.toCollection(ArrayList::new));
根据这个问题,使用java 1.7的答案是:
ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));
但是,最好始终使用界面:
List<Element> arraylist = Arrays.<Element>asList(array);
可以使用以下3种方法从Array创建ArrayList。
String[] array = {"a", "b", "c", "d", "e"};
//Method 1
List<String> list = Arrays.asList(array);
//Method 2
List<String> list1 = new ArrayList<String>();
Collections.addAll(list1, array);
//Method 3
List<String> list2 = new ArrayList<String>();
for(String text:array) {
list2.add(text);
}
new ArrayList<>(Arrays.asList(array));