给定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>,则会出现编译器错误。
其他回答
尽管这个问题有很多完美的书面答案,我还是会补充我的意见。
假设你有Element〔〕array={new Element(1),new Element(2),new Element(3)};
可以通过以下方式创建新的ArrayList
ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));
ArrayList<Element> arraylist_2 = new ArrayList<>(
Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));
// Add through a collection
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);
它们非常支持ArrayList的所有操作
arraylist_1.add(new Element(4)); // or remove(): Success
arraylist_2.add(new Element(4)); // or remove(): Success
arraylist_3.add(new Element(4)); // or remove(): Success
但以下操作只返回ArrayList的List视图,而不是实际的ArrayList。
// Returns a List view of array and not actual ArrayList
List<Element> listView_1 = (List<Element>) Arrays.asList(array);
List<Element> listView_2 = Arrays.asList(array);
List<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));
因此,当尝试执行某些ArrayList操作时,它们会给出错误
listView_1.add(new Element(4)); // Error
listView_2.add(new Element(4)); // Error
listView_3.add(new Element(4)); // Error
有关数组链接的列表表示的详细信息。
另一个更新,即将于2014年结束,您也可以使用Java 8完成:
ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));
如果这只是一个列表,则会保存几个字符
List<Element> list = Stream.of(myArray).collect(Collectors.toList());
在Java 9中,您可以使用:
List<String> list = List.of("Hello", "World", "from", "Java");
List<Integer> list = List.of(1, 2, 3, 4, 5);
您可以在java8中执行以下操作
ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());
给定对象数组:
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