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

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

问题描述

我想为测试目的创建一个选项列表。首先,我这样做:

  ArrayList< String> places = new ArrayList< String>(); 
places.add(Buenos Aires);
places.add(Córdoba);
places.add(La Plata);然后我重构代码如下:


pre> ArrayList< String> places = new ArrayList< String>(
Arrays.asList(Buenos Aires,Córdoba,La Plata));有没有更好的方法来做这个?



c>> c>> c> c> c>以任何方式创建新的 List

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

有一点是,有很多类型需要引用 list 实例。



有一些替代方法,例如使用一个实例初始化函数):

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

但是,我不太喜欢那个方法,因为你最终得到的是一个子类 ArrayList 它有一个实例初始化器,并且创建这个类只是为了创建一个对象 - 这似乎对我有点过分。



如果 Project Coin 的收藏文字提案已被接受在Java 7中引入,但不可能是Java 8的一部分。):

  List< String> list = [A,B,C];不幸的是它不会帮助你在这里,因为它将初始化一个不可变的 


$ b <列表
而不是 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");

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?

解决方案

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

The catch is that there is quite a bit of typing required to refer to that list instance.

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

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.

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

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天全站免登陆