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

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

有更好的方法吗?


当前回答

在Java 9中,我们可以很容易地在一行中初始化ArrayList:

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

or

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

Java 9的这种新方法与以前的方法相比有许多优点:

空间效率不可变性线程安全

有关更多详细信息,请参阅本文->List.of和Arrays.asList之间的区别是什么?

其他回答

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

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

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

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

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

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

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

(应该是评论,但太长了,所以是新回复)。正如其他人所提到的,Arrays.asList方法是固定大小的,但这并不是它唯一的问题。它也不能很好地处理继承。例如,假设您有以下内容:

class A{}
class B extends A{}

public List<A> getAList(){
    return Arrays.asList(new B());
}

上述结果导致编译器错误,因为List<B>(这是Arrays.asList返回的)不是List<a>的子类,即使您可以将类型B的object添加到List<a>object。要解决此问题,您需要执行以下操作:

new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))

这可能是实现这一点的最佳方式,特别是如果您需要无边界列表或需要使用继承。