在一行的ArrayList的初始化 [英] Initialization of an ArrayList in one line

查看:150
本文介绍了在一行的ArrayList的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a list of options for testing purposes. At first, I did this:

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

然后我重构了code如下:

Then I refactored the code as follows:

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

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

其实,这可能是最佳的方式来初始化的ArrayList 是你写的方法,因为它并不需要创建任何新的列表

Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

美中不足的是,有需要打字来指列表实例。

有替代品,如做一个匿名内部类与实例初始化(也称为双大括号初始化):

There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):

ArrayList<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};

不过,我不太喜欢这种方法,因为你最终得到的是的ArrayList 其中有一个实例初始化的子类,这个类是刚刚创建创建一个对象 - 这似乎只是有点矫枉过正我

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

什么本来不错了,如果集合字面建议对于项目硬币被接受(这是定于Java 7的推出,但它不太可能是java 8的一部分其一):

What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):

List<String> list = ["A", "B", "C"];

不幸的是它不会帮助你在这里,因为它会初始化一个不可改变的列表而非的ArrayList ,而且,它是尚未公布,如果它永远不会是。

Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.

这篇关于在一行的ArrayList的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆