Initializing Java Collections

Most of us know that an array in Java can be initialized by

1
String[] fruit = new String[] {"apple", "cherry"};

I say “most” and not “all” since arrays aren’t that common in everyday Java usage with all those handy collections around. One of the major (perceived) downsides of those, they’re ugly to initialize.

1
2
 
List fruit = new ArrayList("apple", "cherry");

just doesn’t work and

1
2
3
4
 
List fruit = new ArrayList();
fruit.add("apple");
fruit.add("cherry");

doesn’t look to nice. But did you know, you could do this?

1
2
3
4
5
 
List fruit = new ArrayList() {{
    add("apple");
    add("cherry");
}};

O.K. basically it looks very similar (except for the missing variable names) and it gives the same result so why bother? First it’s optically separated from the rest of the code, thus easily recognized as an initializer for the list. Second it’s not just a new list and two elements added to it. It’s an anonymous subclass of ArrayList with a static initializer, thus an innocent @SuppressWarnings(“serial”) might be needed to silence your compiler’s warnings…