给定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 = ???;
当前回答
可以使用不同的方法进行转换
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
其他回答
您也可以使用Java8中的流来实现这一点。
List<Element> elements = Arrays.stream(array).collect(Collectors.toList());
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);
下面的代码似乎是很好的方法。
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());
使用以下代码将元素数组转换为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]);
}