Sunday, June 19, 2011

Java Double Brace Initialization

Double brace initialization is a combination of two separate process in java. There are two { braces involved in it. If you see two consecutive curly braces { in java code, it is an usage of double brace initialization.

 

Java Double Brace Initialization

First brace is creation of an anonymous inner class. Without considering the second brace if you see the first brace alone then its nothing new for us. We have created many anonymous inner classes in such a way.
Second brace is an initialization block. That too you have seen in it a class for initialization. You may have used a static initialization block. When you use the initialization block for an anonymous inner class it becomes java double brace initialization. The inner class created will have a reference to the enclosing outer class. That reference can be used using the ‘this’ pointer.

 

Example for double brace initialization

class JavaPapers {
....
....
add(new JPanel() {{
setLayout(...);
setBorder(...);
...
}}
);
}

Uses of double brace initialization

Using double brace initialization, we can initialize collections. Though people say, it is easier to initialize a constant collection using double brace initialization. I don’t see any advantage in using double brace initialization to initialize collections. In jdk 1.7 there is going to be an exclusive construct for that. Then java double brace initialization will become completely obsolete.
...
myMethod(
  new ArrayList<String>() {{
     add("java");
     add("jsp");
     add("servlets");
  }}
);
...

Note on double brace initialization

 

Serialization of non-static inner class has an issue. The outer class will also get serialized. Because the inner class has got a reference to the outer class and it is implicit. Since it is implicit, it cannot be marked as transient. This issue is also applicable for double brace initialization.

No comments:

Post a Comment