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.
I am searching for the shortest way (in code) to initialize list of strings
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are various options. Personally I like using Guava:
(Guava’s a library worth having anyway, of course 🙂
Using just the JDK, you could use:
Note that this will return an
ArrayList, but that’s not the normaljava.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:
… whereas if you statically import
asListit looks a little odder.Another Guava option, if you don’t want a modifiable-in-any-way list:
I typically want to either have a completely mutable list (in which case
Lists.newArrayListis best) or a completely immutable list (in which caseImmutableList.ofis best). It’s rare that I really want a mutable-but-fixed-size list.