Double Brace Initialization

In the “where have you been all my life” category, comes this gem sent to me by my boss.  It’s this link to a wonderful site that contains a wealth of information on Java idioms.  This one specifically deals with initializing collections using a double curly brace syntax.  For example:

Map<String, Object> myMap = new HashMap<String, Object>(){{
          put("today", new Date());
          put("pet", new Dog("Fido"));
          put("foo", bar);

That’s all there is to it. As the linked post demonstrates, this works with Lists, Sets and about any Collection you can imagine. Be sure to check out the rest of the idioms listed on the site’s main page.

It’s a wiki filled with excellent information on a wide variety of Java programming subjects.  As with any complex subject, there are disagreements over certain aspects of the topics presented.  However, the competing points of view are presented in a respectful, conversational format that are very informative and will challenge your longheld views.

This entry was posted in Code and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s