给定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<Element>类型列表的lambda表达式(1) 没有未检查的强制转换(2) 而不创建第二个列表(使用例如asList())
ArrayList<Element>list=Stream.of(array).collector(Collectors.toCollection(ArrayList::new));
其他回答
另一种简单的方法是使用for each循环将数组中的所有元素添加到新的ArrayList中。
ArrayList<Element> list = new ArrayList<>();
for(Element e : array)
list.add(e);
可以使用不同的方法进行转换
List<Element>List=Arrays.asList(array);List<Element>List=newArrayList();Collections.addAll(列表,数组);Arraylist列表=新Arraylist();list.addAll(Arrays.asList(array));
有关详细信息,请参阅http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html
Java 9
在Java9中,可以使用List.of静态工厂方法来创建List文本。类似以下内容:
List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));
这将返回一个包含三个元素的不可变列表。如果需要可变列表,请将该列表传递给ArrayList构造函数:
new ArrayList<>(List.of(// elements vararg))
JEP 269:便利工厂收集方法
JEP269为Java集合API提供了一些方便的工厂方法。这些不可变的静态工厂方法内置在Java9和更高版本的List、Set和Map接口中。
您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:
List<Element> arraylist = Arrays.asList(array);
尽管这个问题有很多完美的书面答案,我还是会补充我的意见。
假设你有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
有关数组链接的列表表示的详细信息。