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"); ?
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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With