Compact syntax for instantiating an initializing collection
Solution 1
http://blog.firdau.si/2010/07/01/java-tips-initializing-collection/
List<String> s = Arrays.asList("1", "2");
Solution 2
I guess you're thinking about
collection = new ArrayList<String>() { // anonymous subclass
{ // anonymous initializer
add("1");
add("2");
add("3");
}
}
which, one comapcted, gives
collection = new ArrayList<String>() {{ add("1"); add("2"); add("3"); }}
FUGLY, to say the least. However, there is a variant to the Arrays.asList method : Arrays.asList(T...a)
which provides comapcity and readability. As an example, it gives the following line of code :
collection = new ArrayList<String>(Arrays.asList("1", "2", "3")); // yep, this one is the shorter
And notice you don't create an anonymous subclass of ArrayList of dubious use.
Solution 3
Maybe that was
Collection<String> collection = new ArrayList<String>() {{
add("foo");
add("bar");
}};
Also known as double-bracket initialization.
Solution 4
You could create an utility function:
@SafeVarargs
public static <T> List<T> listOf(T ... values) {
return new ArrayList<T>(Arrays.asList(values));
}
So you could call it like:
collection = MyUtils.listOf("1", "2", "3");
That way, you can populate a list very easily, and still keep it mutable.
Dónal
I earn a living by editing text files. I can be contacted at: [email protected] You can find out about all the different kinds of text files I've edited at: My StackOverflow Careers profile
Updated on December 30, 2020Comments
-
Dónal over 3 years
I'm looking for a compact syntax for instantiating a collection and adding a few items to it. I currently use this syntax:
Collection<String> collection = new ArrayList<String>(Arrays.asList(new String[] { "1", "2", "3" }));
I seem to recall that there's a more compact way of doing this that uses an anonymous subclass of
ArrayList
, then adds the items in the subclass' constructor. However, I can't seem to remember the exact syntax.