A bet you don’t know about these in Java!

Double Brace Initialization

Probably a lot of time you whish to initialize a collection in Java with default values at construction time, but without doing the sequence stuff like this one (too many statements):

How to do it?

Using a static method asList (probably you know about this one!)

Functional style, fewer lines, very precise, and clear!

Using Double Brace Initialization

If you think a little about it you will see nothing knew, but may surprise you this way of initialization!

Is this a hidden feature in Java? No!

If you know something about anonymous classes and anonymous constructors, nothing here is new!

The first “{“ is creating an anonymous subclass of ArrayList, and the second “{“ is used to create an anonymous constructor.

Let me put the code in another way:

More clear now?

Java has some hidden gems that they deserve to be found!


del.icio.us Tags: ,
Technorati Tags: ,
43 Things Tags: ,


  1. 3biga says:

    You lost a bet. I knew that.

  2. Serandel says:

    In fact, it’s not a constructor, it’s an initialization block. (What the heck was an anonymous constructor, by the way? :D) It runs BEFORE any constructor and, of course, you’re free to use whichever constructor rocks your boat, with or without parameters. For example:

    // Using the constructor with initialCapacity
    List cars = new ArrayList(5){{

    What were we betting? 🙂

  3. josedacruz says:

    You are correct. I’ve called “anonymous constructor” just to give some highlight to the underneath behavior of the initialization block. But the correct term it’s in fact “anonymous initialization block”.
    About the betting…;)

  4. Kofa says:

    I find that I don’t really need initialisation if the value changes afterwards, and if the value is constant, Arrays.asList or Guava’s ImmutableList (and similar immutable collections + builders) do the job nicely.
    I knew the anonymous collection subclass (‘double brace’) solution, but don’t like the idea of creating new classes just to initialise a collection.

  5. really? says:

    There is a strong reason for why you SHOULD NOT use that kind of code: efficiency.

    All of the techniques that you’ve presented are significantly slower when compared to the “standard way”.

    Just do some quick timing and you can see:
    44558 ns
    135896 ns
    538808 ns

    but if you dive into what the java libraries are doing, it’s easily clear why the presented options are not good

  6. josedacruz says:

    I agree with you. I just want to show that there are things in Java “more advanced” and more “functional style” than most of people know. Thanks for the comment!

Leave a Reply

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

Bad Behavior has blocked 115 access attempts in the last 7 days.

Hyper Smash