Monday, October 26, 2009

Double Brace Initialization in Java

Sometimes Double Brace Initialization is treated as a hidden feature of Java, But let's look closer to the syntax. In a normal way when we are declaring and initializing Collection we would use following code snippet:


 List normal = new ArrayList();
normal.add("string_1");
normal.add("string_2");
normal.add("string_3");

Now we can use double brace initialization and rewrite code:

 List list = new ArrayList() {{
add("string_1");
add("string_2");
add("string_3");
}};

What we got is not a new feature, we are just declaring anonymous class and second braces creates an initializer block, which will be invoked when class is created.
As we can see this approach is nice for initializations and we can use it in following case:

     method(new ArrayList() {{
add("string_1");
add("string_2");
add("string_3");
}});


But it is slightly inefficient, instead of creating new instance of class we are creating new class and if we have 100 such initializations we will receive 100 new classes. I don't suggest to use it under high performance requirements.

9 comments:

Shantanu Kumar said...

I covered something similar here: http://charsequence.blogspot.com/2009/08/almost-literals-initializing-java.html

gleichmann said...

Another drawback you may be aware of:

http://gleichmann.wordpress.com/2008/11/25/initializer-build-idiom-facts-and-fallacies/

Greetings

Mario

Erik said...

Also, never use this kind of initialization if you are coding methods that may be used remotely. As it creates an anonymous class, the client will never dispose of this class. So the method that will use or return the list will never been found.

I used to use the double brace init, I no more do.

Nick Stolwijk said...

Take a look at Google Collections. With it, it would be something like:

List<String> stringList = Lists.newArrayList("string1", "string2", "string3");

rachvela said...

IMO Google Collections is better than standard JDK collections, It has many useful features and data structures

schup said...

What is wrong with

List<String> list = Arrays.asList("string1", "string2", "string3");

Already part of the JDK - no additional library needed.

xeonblue said...

Because Arrays.asList creates an immutable list. Or at the very least is missing features of an actual ArrayList.

xeonblue said...

I misspoke.. it creates a fixed size list.

rachvela said...

@schup
Arrays.asList() method returns a fixed-size list backed by the specified array therefore it is not applicable in most cases. But you can use it as a bridge.

Post a Comment