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

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

问题描述

我正在寻找初始化字符串列表和字符串数组的最短方法(在代码中),即包含列表/数组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.

推荐答案

有多种选择.我个人喜欢使用 Guava:

There are various options. Personally I like using Guava:

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

(当然,Guava 是一个值得拥有的图书馆:)

(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.

我个人更喜欢 Guava 版本,因为它清楚地说明了正在发生的事情(将返回的列表实现).如果您静态导入方法,仍然很清楚发生了什么:

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 它看起来有点奇怪.

... whereas if you statically import asList it looks a little odder.

另一个番石榴选项,如果你不想要一个可修改的任何方式列表:

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天全站免登陆