Monthly Archives: July 2008

Double Brace Initialization in Java

When I was working on my thesis for graduate school I spent months reading all that I could on optimizations that Java coders could consciously utilize while coding. While that was as exciting as it sounds*, I did manage to stumble across a few Java idioms that I’m surprised I don’t see used more often. One of my favorite idioms that I still use from time to time is called Double Brace Initialization. It’s a simple way to initialize collections, and I personally feel that it makes code more readable.

Instead of this:

private Map map = new HashMap();
map.put(obj1, 3);
map.put(obj2, 4);
/*  yada yada yada */

You can do this:

private Map map = new HashMap(){{
put(obj1, 3);
put(obj2, 4);
/* yada yada yada */
}}

The first brace creates an anonymous inner class, and the second brace creates an initializer block that is executed when the anonymous class is created.

__

*it really wasn’t.