给定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 = ???;
当前回答
给定对象数组:
Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};
将数组转换为列表:
List<Element> list = Arrays.stream(array).collect(Collectors.toList());
将数组转换为ArrayList
ArrayList<Element> arrayList = Arrays.stream(array)
.collect(Collectors.toCollection(ArrayList::new));
将数组转换为LinkedList
LinkedList<Element> linkedList = Arrays.stream(array)
.collect(Collectors.toCollection(LinkedList::new));
打印列表:
list.forEach(element -> {
System.out.println(element.i);
});
输出,输出
1
2
3
其他回答
还有一种方法可以用于将数组转换为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;
}
鉴于:
Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
最简单的答案是:
List<Element> list = Arrays.asList(array);
这会很好的。但需要注意的是:
从asList返回的列表大小固定。因此,如果您希望能够在代码中添加或删除返回列表中的元素,则需要将其包装在新的ArrayList中。否则,您将获得UnsupportedOperationException。从asList()返回的列表由原始数组支持。如果修改原始数组,列表也将被修改。这可能令人惊讶。
在调用Arrays接口时,还可以使用多态性声明ArrayList,如下所示:
List<Element>arraylist=newArrayList<Integer>(Arrays.asList(array));
例子:
Integer[] array = {1}; // autoboxing
List<Integer> arraylist = new ArrayList<Integer>(Arrays.asList(array));
这应该是一种魅力。
使用以下代码将元素数组转换为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]);
}
new ArrayList<>(Arrays.asList(array));