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

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

有更好的方法吗?


当前回答

尝试使用以下代码行:

Collections.singletonList(provider)

其他回答

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

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

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

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

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

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

为什么不做一个简单的实用函数来实现这一点呢?

static <A> ArrayList<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}

“ll”代表“文字列表”。

ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");

使用Guava,您可以写:

ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");

在Guava中还有其他有用的静态构造函数。你可以在这里了解他们。

尝试使用以下代码行:

Collections.singletonList(provider)