给定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

其他回答

嗨,你可以使用这行代码,这是最简单的方法

 new ArrayList<>(Arrays.asList(myArray));

或者如果您使用Java 9,也可以使用以下方法:

List<String> list = List.of("Hello", "Java"); 
List<Integer> list = List.of(1, 2, 3);

使用以下代码将元素数组转换为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]);
}

使用Stream(从java 16开始)

new ArrayList<>(Arrays.stream(array).toList());

自从Java 8以来,有一种更简单的转换方法:

import java.util.List;    
import static java.util.stream.Collectors.toList;

public static <T> List<T> fromArray(T[] array) {
    return Arrays.stream(array).collect(toList());
}
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);