给定Element[]类型的数组:

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

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

ArrayList<Element> arrayList = ???;

当前回答

您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:

List<Element> arraylist = Arrays.asList(array);

其他回答

使用以下代码

Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) Arrays.asList(array);

另一种方式(虽然本质上等同于新的ArrayList(array.asList(array))解决方案的性能:

Collections.addAll(arraylist, array);

下面的代码似乎是很好的方法。

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

给定对象数组:

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

鉴于:

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

最简单的答案是:

List<Element> list = Arrays.asList(array);

这会很好的。但需要注意的是:

从asList返回的列表大小固定。因此,如果您希望能够在代码中添加或删除返回列表中的元素,则需要将其包装在新的ArrayList中。否则,您将获得UnsupportedOperationException。从asList()返回的列表由原始数组支持。如果修改原始数组,列表也将被修改。这可能令人惊讶。