我想创建一个用于测试的选项列表。起初,我这样做:
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
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");
声明:我是算盘通用的开发者。
在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之间的区别是什么?