给定Element[]类型的数组:

Element[] array = {new Element(1), new Element(2), new Element(3)};

如何将此数组转换为ArrayList<Element>类型的对象?

ArrayList<Element> arrayList = ???;

当前回答

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

其他回答

在java中,主要有3种方法将数组转换为arrayList

使用Arrays.asList()方法:将所需的数组传递给此方法,并获取List对象,并将其作为参数传递给ArrayList类的构造函数。List<String>List=Arrays.asList(array);System.out.println(列表);Collections.addAll()方法-在使用此方法之前创建一个新列表,然后使用此方法将数组元素添加到现有列表中。List<String>list1=newArrayList<String>();Collections.addAll(列表1,数组);System.out.println(列表1);迭代方法-创建新列表。循环数组并将每个元素添加到列表中。List<String>list2=newArrayList<String>();for(字符串文本:数组){list2.add(文本);}System.out.println(列表2);

你也可以参考这个文档

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

给定对象数组:

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

另一种简单的方法是使用for each循环将数组中的所有元素添加到新的ArrayList中。

ArrayList<Element> list = new ArrayList<>();

for(Element e : array)
    list.add(e);

使用Stream(从java 16开始)

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