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

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

有更好的方法吗?


当前回答

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

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

其他回答

对我来说,Arrays.asList()是最好且方便的方法。我总是喜欢这样初始化。如果您是Java集合的初学者,那么我希望您参考ArrayList初始化

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

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

您可以使用以下语句:

代码段:

String [] arr = {"Sharlock", "Homes", "Watson"};

List<String> names = Arrays.asList(arr);

这是算盘常见的代码

// ArrayList
List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
// HashSet
Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
// HashMap
Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// Or for Immutable List/Set/Map
ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// The most efficient way, which is similar with Arrays.asList(...) in JDK. 
// but returns a flexible-size list backed by the specified array.
List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");

声明:我是算盘通用的开发者。

import com.google.common.collect.ImmutableList;

....

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