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

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

有更好的方法吗?


当前回答

正如汤姆所说:

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

但是,既然你抱怨想要一个ArrayList,你应该首先知道ArrayList是List的一个子类,你可以简单地添加这一行:

ArrayList<String> myPlaces = new ArrayList(places);

不过,这可能会让你抱怨“表现”。

在这种情况下,这对我来说没有意义,为什么,因为您的列表是预定义的,所以它没有被定义为数组(因为在初始化时大小是已知的)。如果这是你的选择:

String[] places = {"Buenos Aires", "Córdoba", "La Plata"};

如果您不关心细微的性能差异,那么您也可以非常简单地将数组复制到ArrayList:

ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));

好吧,但未来你需要的不仅仅是地名,还需要国家代码。假设这仍然是一个预定义的列表,在运行时不会更改,那么使用枚举集是合适的,如果将来需要更改列表,则需要重新编译。

enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}

将变成:

enum Places {
    BUENOS_AIRES("Buenos Aires",123),
    CORDOBA("Córdoba",456),
    LA_PLATA("La Plata",789);

    String name;
    int code;
    Places(String name, int code) {
      this.name=name;
      this.code=code;
    }
}

枚举有一个静态值方法,该方法返回一个数组,该数组按声明顺序包含枚举的所有值,例如:

for (Places p:Places.values()) {
    System.out.printf("The place %s has code %d%n",
                  p.name, p.code);
}

在这种情况下,我想你不需要你的ArrayList。

P.S.Randyaa演示了使用静态实用程序方法Collections.addAll的另一种好方法。

其他回答

最简单的方法:可以使用此方法向任意类型的集合(如ArrayList和HashSet)添加多个元素

ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");

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

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

import com.google.common.collect.ImmutableList;

....

List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

这是Arrays.asList的实现,因此您可以使用

ArrayList<String> arr = (ArrayList<String>) Arrays.asList("1", "2");

是的,借助数组,您可以在一行中初始化数组列表,

List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");