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):

// Initialize a cars collection
List<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ferrari");

// call the method
someMethod(cars);

How to do it?

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

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

// Initialize the collection (fewer statements!)
List<String> cars = new ArrayList<>(Arrays.asList("Volvo", "BMW", "Ferrari"));

// call the method
someMethod(cars);

Using Double Brace Initialization

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

// Initialize the collection
List<String> cars = new ArrayList<String>(){{
            add("Volvo");
            add("BMW");
            add("Ferrari");
        }};

// Call the method
someMethod(cars);

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:

// The collection creation!
trickList<String> cars = new ArrayList<String>()
        // The anonymous subclass 
        {
            // The anonymous constructor
            {
                add("Volvo");
                add("BMW");
                add("Ferrari");
            }
        };

// The method call
someMethod(cars);

More clear now?

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

 

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

7 Comments

  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){{
    add(“Volvo”);
    add(“BMW”);
    add(“Ferrari”);
    }};

    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 *


4 − = two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

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

Hyper Smash