我想创建一个用于测试的选项列表。起初,我这样做:
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中,您无法做到
ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
如前所述,您需要执行双括号初始化:
List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};
但这可能会迫使您添加注释@SuppressWarnings(“串行”)或生成一个令人讨厌的串行UUID。大多数代码格式化程序也会将其展开为多个语句/行。
或者你也可以这样做
List<String> places = Arrays.asList(new String[] {"x", "y" });
但您可能需要执行@SuppressWarnings(“未选中”)。
此外,根据javadoc,您应该能够做到这一点:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
但我无法用JDK1.6编译它。
使用Eclipse集合,您可以编写以下内容:
List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
您还可以更具体地了解类型,以及它们是可变的还是不可变的。
MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");
您也可以对套装和包进行同样的操作:
Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");
Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");
注意:我是Eclipse集合的提交人。