给定Element[]类型的数组:
Element[] array = {new Element(1), new Element(2), new Element(3)};
如何将此数组转换为ArrayList<Element>类型的对象?
ArrayList<Element> arrayList = ???;
给定Element[]类型的数组:
Element[] array = {new Element(1), new Element(2), new Element(3)};
如何将此数组转换为ArrayList<Element>类型的对象?
ArrayList<Element> arrayList = ???;
当前回答
下面的代码似乎是很好的方法。
new ArrayList<T>(Arrays.asList(myArray));
其他回答
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());
另一种方式(虽然本质上等同于新的ArrayList(array.asList(array))解决方案的性能:
Collections.addAll(arraylist, array);
使用Stream(从java 16开始)
new ArrayList<>(Arrays.stream(array).toList());
您可能只需要一个List,而不是ArrayList。在这种情况下,您只需执行以下操作:
List<Element> arraylist = Arrays.asList(array);
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> list = List.of(array);
or
List<Element> list = Arrays.asList(array);
这两种方法都可以将其转换为列表。