给定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 = ???;
当前回答
尽管这个问题有很多完美的书面答案,我还是会补充我的意见。
假设你有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
有关数组链接的列表表示的详细信息。
其他回答
在java中,主要有3种方法将数组转换为arrayList
使用Arrays.asList()方法:将所需的数组传递给此方法,并获取List对象,并将其作为参数传递给ArrayList类的构造函数。List<String>List=Arrays.asList(array);System.out.println(列表);Collections.addAll()方法-在使用此方法之前创建一个新列表,然后使用此方法将数组元素添加到现有列表中。List<String>list1=newArrayList<String>();Collections.addAll(列表1,数组);System.out.println(列表1);迭代方法-创建新列表。循环数组并将每个元素添加到列表中。List<String>list2=newArrayList<String>();for(字符串文本:数组){list2.add(文本);}System.out.println(列表2);
你也可以参考这个文档
另一种方式(虽然本质上等同于新的ArrayList(array.asList(array))解决方案的性能:
Collections.addAll(arraylist, array);
另一个更新,即将于2014年结束,您也可以使用Java 8完成:
ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));
如果这只是一个列表,则会保存几个字符
List<Element> list = Stream.of(myArray).collect(Collectors.toList());
您可以使用Cactos创建ArrayList(我是开发人员之一):
List<String> names = new StickyList<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
不能保证该对象实际上是ArrayList类。如果您需要该担保,请执行以下操作:
ArrayList<String> list = new ArrayList<>(
new StickyList<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
)
);
正如大家所说的那样
new ArrayList<>(Arrays.asList("1","2","3","4"));
创建数组的最新常用方法是observableArrays
ObservableList:允许侦听器在发生更改时跟踪更改的列表。
对于Java SE,您可以尝试
FXCollections.observableArrayList(new Element(1), new Element(2), new Element(3));
根据Oracle Docs
可观测阵列列表()创建一个由数组列表支持的新的空可观察列表。可观测阵列列表(E…项)创建一个新的可观察数组列表,其中添加了项。
更新Java 9
在Java 9中也有点简单:
List<String> list = List.of("element 1", "element 2", "element 3");