翻译:https://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line
常规的几中用法:
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<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
List<String> list = ["A", "B", "C"];
上面这种方法慎用。它创建了一个内容固定的数组,是不允许修改的。另外,这种用法不是java支持的。
Unfortunately it won't help you here, as it will initialize an immutable List
rather than an ArrayList
, and furthermore, it's not available yet, if it ever will be.
另外一种用法:
如果你的数组只有一个元素的话,请用下面的用法。在这里,“places”是一个内容固定的数组,任何对数组的更新操作都会有一场UnsupportedOperationException
抛出。(Or if you have only one element:This would mean that places
is immutable (trying to change it will cause an UnsupportedOperationException
exception to be thrown)).
List<String> places = Collections.singletonList("Buenos Aires");
如果你的数组不止一个元素的话,可以用下面这种方式(If you need a list of several objects:)
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");
在Java10 及以后的版本中(In Java 10 or later:)
var strings = List.of("foo", "bar", "baz");
在java 9 及以后的版本中(In Java 9 or later:)
List<String> strings = List.of("foo", "bar", "baz");
在Java8 以及之前的版本中(Java 8 or earlier:)
List<String> strings = Arrays.asList("foo", "bar", "baz");
You can make Arrays.asList
even shorter with a static import:
import static java.util.Arrays.asList;
List<String> strings = asList("foo", "bar", "baz");
或者使用流(or using Stream
:)
import static java.util.stream.Collectors.toCollection;
ArrayList<String> strings = Stream.of("foo", "bar")
.collect(toCollection(ArrayList::new));
strings.add("baz");
最近看了不少国内的帖子,完全是拿来主义,结果却说是自己的原创,而且翻译的也是呵呵。。。尊重原创,尊重知识产权