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

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

有更好的方法吗?


当前回答

使用Guava,您可以写:

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

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

其他回答

对于java-9和更高版本,正如JEP269:集合的便利工厂方法中所建议的,这可以使用集合文本实现,现在使用-

List<String> list = List.of("A", "B", "C");

Set<String> set = Set.of("A", "B", "C");

类似的方法也适用于Map-

Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")

这与@coobird所述的“收藏文字”提案类似。JEP中也有进一步澄清-


选择

语言更改已被考虑过多次,但均被拒绝:项目硬币提案,2009年3月29日项目硬币提案,2009年3月30日JEP 186关于lambda开发的讨论,2014年1月至3月语言建议被搁置,而不是基于图书馆的建议,因为此消息中总结。

相关:在Java9中重载集合的便利工厂方法有什么意义

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

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

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

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

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

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

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

Java 9有以下方法来创建不可变列表:

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

如果需要,它很容易适于创建可变列表:

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

类似的方法可用于“集”和“贴图”。