给定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);
其他回答
下面的代码似乎是很好的方法。
new ArrayList<T>(Arrays.asList(myArray));
另一个更新,即将于2014年结束,您也可以使用Java 8完成:
ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));
如果这只是一个列表,则会保存几个字符
List<Element> list = Stream.of(myArray).collect(Collectors.toList());
使用以下代码
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) Arrays.asList(array);
使用Stream(从java 16开始)
new ArrayList<>(Arrays.stream(array).toList());
您也可以使用Java8中的流来实现这一点。
List<Element> elements = Arrays.stream(array).collect(Collectors.toList());