3

I have come across with this syntax while reading some others code

Map<String, String> map = new HashMap<String, String>() {
    { 
         put("a", "b");
    }
};

I know how to use anonymous inner class but this seems something different. Could somebody explain me how exactly the above works and how it is different from Map<String, String> map = new HashMap<String, String>(); map.put("a", "b"); ?

RP-
  • 5,827
  • 2
  • 27
  • 46

2 Answers2

6

You are basically creating a anonymous class instance and specifying an instance initializer. Think of it in terms of a normal class, e.g.:

class Person {

  String age, name;

  List<String> hobbies;

  {
    hobbies = new ArrayList<String>();
  }

  public Person(String name, String age) {
    this.name = name;
    this.age = age;
  } 

}

What do you think the above is doing? Your anonymous class is doing something similar. :)

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • Correct, as soon as `new Person(...)` called, even hobbies gets initialized along with name and age. Thanks! – RP- Aug 01 '12 at 11:47
  • Yup, you got that right. Also make sure you go through the thread mentioned in the comment to your original post. – Sanjay T. Sharma Aug 01 '12 at 11:59
2

As Sanjay T. Sharma clearly explained, it's creating anonymous class instance. In fact, it is extending java.util.HashMap. Consider the following code:

package com.test;

import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        Map<String, String> mapSimple = new HashMap<String, String>();
        System.out.println("Simple java.util.HashMap:");
        System.out.println("\t" + mapSimple.getClass());

        Map<String, String> map = new HashMap<String, String>() {
            {
                put("a", "b");
            }
        };

        System.out.println("Anonymous class based on java.util.HashMap:");
        System.out.println("\t" + map.getClass());
        System.out.println("\t" + map.getClass().getSuperclass());
    }
}

It produces the following output:

Simple java.util.HashMap:
    class java.util.HashMap
Anonymous class based on java.util.HashMap:
    class com.test.Demo$1
    class java.util.HashMap

Pay attention to the name of such anonymous class, and that this class extends java.util.HashMap.

Art Licis
  • 3,619
  • 1
  • 29
  • 49