Alex Rivera | Logout

Compact syntax for instantiating an initializing collection

Asked 2010-09-22T13:02:26.327
33

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.

Edit
Report

1 Answer

5

Maybe that was

Collection<String> collection = new ArrayList<String>() {{
    add("foo");
    add("bar");
}};

Also known as double-bracket initialization.

answered 2010-09-22T13:05:30.023

Your Answer