What The Double Curly Brace!!!

It’s not everyday you get to wow your co-workers with a bit of programming esoterica. As developers we love to get one over our co-workers, especially when it comes to weird bits of the language. Yes, it’s childish and 99 times out of 1000 it has no useable benefit but that hundredth time tends to be a doozy and I regard this kind of intellectual one-upmanship as a positive thing. At the root of it, we are knowledge workers and the more we know the better we are so why shouldn’t we try to learn as much as possible.

But this was not one of those times. This was just something that I’d seen in passing a few months ago that amused me but since it stumped the 3 best developers on my floor I thought I’d put it down, so here it is:

package com.bloodredsun;

import java.util.*;

public class DoubleCurlyBrace {

    private static List myList = new ArrayList(){{
        add("Hello ");
        add("World");
    }};

}

.
So what we have here is an instance initializer block for an anonymous inner class. The class of myList is actually com.bloodredsun.DoubleCurlyBrace$1 and not a java.util.ArrayList. While this is admittedly cool, the syntax is so unusual that I threatened to throw heavy things at anyone in the team that actually uses this. I will report back on the fate of anyone that does… 😉

2 thoughts on “What The Double Curly Brace!!!

  1. Lukas Eder

    It’s definitely worth mentioning that the double curly brace antipattern is one of the most subtle sources of terrible memory leak bugs. We’ve recently blogged about that here:

    http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/

    In your own example, you won’t suffer from this, as your List is a static member. But as soon as you make that an instance member, your anonymous ArrayList sub type will keep a reference to the enclosing DoubleCurlyBrace instance.

    Reply
    1. Martin Post author

      Thanks Lukas, that’s a far better reason not to use it and probably one that people will not be aware of while they are trying to be clever.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.