initializer block

HashMap map = new HashMap() {
{
put(“item1”, “This is item1”);
put(“item2”, “This is item2”);
}};

This is some syntax I found while googling for something.  Well, if you look at it closely, all we are doing is extending the HashMap and creating a anonymous class that has a initializer block the puts stuff into the hashmap. Simple!

If you are not famliar, an Initializer block is executed before executing the constructor. You may also be interested in static initializer block. (Just google!)

Advertisements

2 Responses to initializer block

  1. Steven says:

    Yes, you can take it one step further and actually put loops into the initialize block.
    Like this:
    HashSet set = new HashSet() { {
    for(int i = 0 ; i <= 11; i++) {
    add("N" + i);
    }

    }};

  2. Steven says:

    So in the case of a headless class is the static modifier_assumed_ when you add the inner-most braces?

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: