Monday, September 28, 2009

Double Brace Initialisation

"Double Brace Initialisation" is one of the lesser known features in Java. It can be useful for initialising collections that have to be passed to other methods.

For example, without double-brace initialisation:

Map<String,String> map = new HashMap <String,String>();
map.put("key","value");
map.put("key2","value2");
printMap(map);
With double-brace initialisation:
printMap(new HashMap <String,String>(){{
            put("key","value");
            put("key2","value2");
        }});
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This only works only for non-final classes because it creates an anonymous subclass.

Don't go too overboard with this because it creates a new anonymous inner class just for making a single object which might not be very efficient! It will also create an additional class file on disk.

Another example:

//double-brace initialisation
List<String> list = new ArrayList<String>(){{
   add("apple");
   add("banana");
}};

//better alternative
List<String> list2 = Arrays.asList("apple","banana");

1 comment:

  1. Javas Double Brace Instatiation makes it a lot easier to read your source code. For review reasons is that important to you and your colleagues. I think most people only see these advantages if nobody uses them: they would be glad to have them.

    A few tips and backgrounds, too: is is about the obstacles and the possibillities with Javas Double Brace Instatiation:
    http://bit.ly/endUIi

    I hope I could help a little.

    ReplyDelete

Note: Only a member of this blog may post a comment.