什么是初始化在java中字符串列表最短的路? [英] What is the shortest way to initialize List of strings in java?

查看:107
本文介绍了什么是初始化在java中字符串列表最短的路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我寻找最短路径(在code)来初始化包含字符串列表和字符串数组,即列表/阵列
S1,S2,S3字符串元素。

I am searching for the shortest way (in code) to initialize list of strings and array of strings, i.e. list/array containing "s1", "s2", "s3" string elements.

推荐答案

有各种选项。我个人喜欢用番石榴

There are various options. Personally I like using Guava:

List<String> strings = Lists.newArrayList("s1", "s2", "s3");

(番石榴是值得拥有一个图书馆,无论如何,当然是:)

(Guava's a library worth having anyway, of course :)

只需使用JDK,你可以使用:

Using just the JDK, you could use:

List<String> strings = Arrays.asList("s1", "s2", "s3");

请注意,这会返回一个的ArrayList ,但那是的的正常的java.util.ArrayList - 这是一个内部是可变的,但是固定大小

Note that this will return an ArrayList, but that's not the normal java.util.ArrayList - it's an internal one which is mutable but fixed-size.

我个人preFER的番石榴版本,它明确是怎么回事(这将返回列表实现)。这也是的还是的清楚是怎么回事,如果你静态导入方法:

Personally I prefer the Guava version as it makes it clear what's going on (the list implementation which will be returned). It's also still clear what's going on if you statically import the method:

// import static com.google.common.collect.Lists.newArrayList;
List<String> strings = newArrayList("s1", "s2", "s3");

...而如果你静态导入 asList 它看起来有点越古怪。

另一个番石榴选项,如果你不想修改,在任何路列表:

Another Guava option, if you don't want a modifiable-in-any-way list:

ImmutableList<String> strings = ImmutableList.of("s1", "s2", "s3");

我通常想的或者的具有完全可变的列表(在这种情况下 Lists.newArrayList 最好)的完全不可变列表(在这种情况下, ImmutableList.of 是最好的)。这是罕见的,我真的希望的一个可变的,但是固定大小的列表。

I typically want to either have a completely mutable list (in which case Lists.newArrayList is best) or a completely immutable list (in which case ImmutableList.of is best). It's rare that I really want a mutable-but-fixed-size list.

这篇关于什么是初始化在java中字符串列表最短的路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆