Thursday, April 14, 2011

Java Double Brace Initialization

This is one of the hidden feature of Java. First of all, lets see some sample code:
ArrayList<String> tags = new ArrayList<String>() {{
add("abc");
add("xyz");
}};
Notice that there are two concurrent curly braces in the code. First brace creates an anonymous inner class and second brace is an instance initializer block that is run while anonymous inner class is instantiated.

Actually, it is just a rewrite of:
ArrayList<String> tags = new ArrayList<String>() {
// Initialization Block
{
add("abc");
add("xyz");
}
};
The inner class created will be having a reference of its enclosing outer class and hence will use "this" pointer to add the string values in the tags arraylist.

So on running the following code:
System.out.println("First Tag: "+tags.get(0));
it will print:
First Tag: abc

No comments: