Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
941 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 :)

Using just the JDK, you could use:

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

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.

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");

... 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");

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...