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

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"));

有更好的方法吗?


当前回答

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

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

其他回答

在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,这会更简单——它必须是ArrayList吗?

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

或者如果您只有一个元素:

List<String> places = Collections.singletonList("Buenos Aires");

这意味着位置是不可变的(尝试更改它将导致引发UnsupportedOperationException异常)。

要创建一个可变列表,即一个具体的ArrayList,您可以从不可变列表中创建一个ArrayList:

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

并导入正确的软件包:

import java.util.Arrays;
public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

这是Arrays.asList的实现,因此您可以使用

ArrayList<String> arr = (ArrayList<String>) Arrays.asList("1", "2");

如果您需要大小为1的简单列表:

List<String> strings = new ArrayList<String>(Collections.singletonList("A"));

如果需要多个对象的列表:

List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");

有趣的是,没有列出带有另一个重载Stream::collect方法的一行

ArrayList<String> places = Stream.of( "Buenos Aires", "Córdoba", "La Plata" ).collect( ArrayList::new, ArrayList::add, ArrayList::addAll );