Java,How to inlization arraylist in one line如何一行初始化ArrayList

翻译: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");

最近看了不少国内的帖子,完全是拿来主义,结果却说是自己的原创,而且翻译的也是呵呵。。。尊重原创,尊重知识产权

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值