我想创建一个用于测试的选项列表。起初,我这样做:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

然后,我将代码重构如下:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

有更好的方法吗?


当前回答

最简单的方法:可以使用此方法向任意类型的集合(如ArrayList和HashSet)添加多个元素

ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");

其他回答

import com.google.common.collect.ImmutableList;

....

List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");

实际上,可以在一行中完成:

Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})

对我来说,Arrays.asList()是最好且方便的方法。我总是喜欢这样初始化。如果您是Java集合的初学者,那么我希望您参考ArrayList初始化

在Java中,您无法做到

ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

如前所述,您需要执行双括号初始化:

List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};

但这可能会迫使您添加注释@SuppressWarnings(“串行”)或生成一个令人讨厌的串行UUID。大多数代码格式化程序也会将其展开为多个语句/行。

或者你也可以这样做

List<String> places = Arrays.asList(new String[] {"x", "y" });

但您可能需要执行@SuppressWarnings(“未选中”)。

此外,根据javadoc,您应该能够做到这一点:

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

但我无法用JDK1.6编译它。

只需使用以下代码即可。

List<String> list = new ArrayList<String>() {{
            add("A");
            add("B");
            add("C");
}};