给定Element[]类型的数组:

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

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

ArrayList<Element> arrayList = ???;

当前回答

鉴于:

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

最简单的答案是:

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

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

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

其他回答

如果数组是基元类型,则给定的答案将不起作用。但自从Java 8以来,您可以使用:

int[] array = new int[5];
Arrays.stream(array).boxed().collect(Collectors.toList());

您也可以使用Java8中的流来实现这一点。

 List<Element> elements = Arrays.stream(array).collect(Collectors.toList()); 

Java8的Arrays类提供了一个stream()方法,该方法具有接受基元数组和Object数组的重载版本。

/**** Converting a Primitive 'int' Array to List ****/

int intArray[] = {1, 2, 3, 4, 5};

List<Integer> integerList1 = Arrays.stream(intArray).boxed().collect(Collectors.toList());

/**** 'IntStream.of' or 'Arrays.stream' Gives The Same Output ****/

List<Integer> integerList2 = IntStream.of(intArray).boxed().collect(Collectors.toList());

/**** Converting an 'Integer' Array to List ****/

Integer integerArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

List<Integer> integerList3 = Arrays.stream(integerArray).collect(Collectors.toList());

使用以下代码

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

使用Stream(从java 16开始)

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