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

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

有更好的方法吗?


当前回答

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

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

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

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

其他回答

使用Array.asList(“布宜诺斯艾利斯”、“科尔多瓦”、“拉普拉塔”);是正确的。但任何对Arrays.asList()的调用如果没有参数或只有一个参数,都可以用对Collections.singletonList()或Collections.emptyList()进行替换,这样可以节省一些内存。

注意:Collections.singletonList()返回的列表是不可变的,而列表返回的Arrays.asList()允许调用set()方法。在极少数情况下,这可能会破坏代码。

在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编译它。

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

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

对于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中重载集合的便利工厂方法有什么意义

import com.google.common.collect.ImmutableList;

....

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