Dón*_*nal 23 java collections initialization
我正在寻找一个紧凑的语法来实例化一个集合并添加一些项目.我目前使用这种语法:
Collection<String> collection =
new ArrayList<String>(Arrays.asList(new String[] { "1", "2", "3" }));
Run Code Online (Sandbox Code Playgroud)
我似乎记得有一个更紧凑的方法,使用匿名子类ArrayList,然后添加子类的构造函数中的项目.但是,我似乎无法记住确切的语法.
nan*_*nda 30
http://blog.firdau.si/2010/07/01/java-tips-initializing-collection/
List<String> s = Arrays.asList("1", "2");
Run Code Online (Sandbox Code Playgroud)
我想你在考虑
collection = new ArrayList<String>() { // anonymous subclass
{ // anonymous initializer
add("1");
add("2");
add("3");
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个共同制定的
collection = new ArrayList<String>() {{ add("1"); add("2"); add("3"); }}
Run Code Online (Sandbox Code Playgroud)
最后,至少可以说.但是,Arrays.asList方法有一个变体:Arrays.asList(T...a)它提供comapcity和可读性.作为示例,它提供以下代码行:
collection = new ArrayList<String>(Arrays.asList("1", "2", "3")); // yep, this one is the shorter
Run Code Online (Sandbox Code Playgroud)
请注意,您不会创建可疑使用的ArrayList的匿名子类.
也许那是
Collection<String> collection = new ArrayList<String>() {{
add("foo");
add("bar");
}};
Run Code Online (Sandbox Code Playgroud)
也称为双括号初始化。
从JDK9开始,您可以使用工厂方法:
List<String> list = List.of("foo", "bar", "baz");
Set<String> set = Set.of("foo", "bar", "baz");
Run Code Online (Sandbox Code Playgroud)