给定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)};

List<Element> list = List.of(array);

or

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

这两种方法都可以将其转换为列表。

其他回答

还有一种方法可以用于将数组转换为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;
    }

生成ArrayList<Element>类型列表的lambda表达式(1) 没有未检查的强制转换(2) 而不创建第二个列表(使用例如asList())

ArrayList<Element>list=Stream.of(array).collector(Collectors.toCollection(ArrayList::new));

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

对于正常大小的数组,上面的答案是正确的。如果您有巨大的数组大小并使用java8,您可以使用流来实现。

  Element[] array = {new Element(1), new Element(2), new Element(3)};
  List<Element> list = Arrays.stream(array).collect(Collectors.toList());
Element[] array = {new Element(1), new Element(2), new Element(3)};

List<Element> list = List.of(array);

or

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

这两种方法都可以将其转换为列表。