给定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));
确保myArray的类型与T相同。例如,如果尝试从int数组创建List<Integer>,则会出现编译器错误。
其他回答
对于正常大小的数组,上面的答案是正确的。如果您有巨大的数组大小并使用java8,您可以使用流来实现。
Element[] array = {new Element(1), new Element(2), new Element(3)};
List<Element> list = Arrays.stream(array).collect(Collectors.toList());
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);
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[] { new Element(1), new Element(2), new Element(3) };
最简单的答案是:
List<Element> list = Arrays.asList(array);
这会很好的。但需要注意的是:
从asList返回的列表大小固定。因此,如果您希望能够在代码中添加或删除返回列表中的元素,则需要将其包装在新的ArrayList中。否则,您将获得UnsupportedOperationException。从asList()返回的列表由原始数组支持。如果修改原始数组,列表也将被修改。这可能令人惊讶。
给定对象数组:
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