在一行中初始化 ArrayList [英] Initialization of an ArrayList in one line
问题描述
我想创建一个用于测试目的的选项列表.起初,我是这样做的:
I wanted to create a list of options for testing purposes. At first, I did this:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
然后,我将代码重构如下:
Then, I refactored the code as follows:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
实际上,初始化 ArrayList
的最佳"方法可能就是您编写的方法,因为它不需要创建一个以任何方式新建List
:
Actually, probably the "best" way to initialize the ArrayList
is the method you wrote, as it does not need to create a new List
in any way:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
问题在于,要引用该 list
实例需要进行大量输入.
The catch is that there is quite a bit of typing required to refer to that list
instance.
还有其他选择,例如使用实例初始化程序(也称为双括号初始化")创建匿名内部类:
There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):
ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
然而,我不太喜欢那个方法,因为你最终得到的是 ArrayList
的一个子类,它有一个实例初始化器,而创建那个类只是为了创建一个对象——这对我来说似乎有点矫枉过正.
However, I'm not too fond of that method because what you end up with is a subclass of ArrayList
which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
如果 Collection LiteralsProject Coin 的提案被接受(原定在 Java 7 中引入,但它也不太可能成为 Java 8 的一部分.):
What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):
List<String> list = ["A", "B", "C"];
不幸的是它在这里对你没有帮助,因为它会初始化一个不可变的 List
而不是一个 ArrayList
,此外,它还不可用,如果它会的话
Unfortunately it won't help you here, as it will initialize an immutable List
rather than an ArrayList
, and furthermore, it's not available yet, if it ever will be.
这篇关于在一行中初始化 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!