7

I have a class MyMap which extends java.util.HashMap, the following code works as a block of statements but I don't understand the use of the extra curly braces

MyMap m = new MyMap() {
  {
      put("some key", "some value");
  }
};

Now why do I need the extra curly braces, can't I just do this (but this raises compile error)

MyMap m = new MyMap() {
    put("some key", "some value");
};
K''
  • 5,020
  • 7
  • 33
  • 43
  • 7
    It's called "double brace initialization". Now, you have new search keywords. Related: http://stackoverflow.com/questions/1372113/meaning-of-new-class-initialization-idiom, http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization and http://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java – BalusC Aug 24 '11 at 20:05
  • and it's a dirty hack that should be banned IMO, following it with a initializer (only needs a `;` and putting the name of the var in front of all those methods and maybe an additional `static` following it) does the same without creating a anonymous subclass – ratchet freak Aug 24 '11 at 21:09

2 Answers2

11

This:

MyMap m = new MyMap() {
    ....
};

creates an anonymous inner class, which is a subclass of HashMap.

This:

{
    put("some key", "some value");
}

is an instance initializer. The code is executed when the instance of the anonymous subclass is created.

Richard Fearn
  • 25,073
  • 7
  • 56
  • 55
4

What you're actually doing here is define an anynomous subclass of MyMap, which was probably not your intent... The outermost curly braces are around the class contents. And in Java, you cannot put instructions directly inside a class block: if you need code to be executed when the class is instantiated, you put it into a constructor. That's what the innermost braces are for: they delimit an initializer for your anonymous class.

Now, you probably wanted something like:

MyMap m = new MyMap();
m.put("some key", "some value");

Just create an instance of MyMap and call put on it, no anonymous class involved.

ChrisJ
  • 5,161
  • 25
  • 20
  • "which was probably not your intent"... actually, this construction is considered idiomatic by some. Seems like overkill to me, though. – Karl Knechtel Aug 24 '11 at 21:23