What is Double Brace initialization in Java?

Viewed 113532

What is Double Brace initialization syntax ({{ ... }}) in Java?

13 Answers

Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.

new ArrayList<Integer>() {{
   add(1);
   add(2);
}};

Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.

For a fun application of double brace initialization, see here Dwemthy’s Array in Java.

An excerpt

private static class IndustrialRaverMonkey
  extends Creature.Base {{
    life = 46;
    strength = 35;
    charisma = 91;
    weapon = 2;
  }}

private static class DwarvenAngel
  extends Creature.Base {{
    life = 540;
    strength = 6;
    charisma = 144;
    weapon = 50;
  }}

And now, be prepared for the BattleOfGrottoOfSausageSmells and … chunky bacon!

As pointed out by @Lukas Eder double braces initialization of collections must be avoided.

It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.

Java 9 has introduced convenience methods List.of, Set.of, and Map.of, which should be used instead. They're faster and more efficient than the double-brace initializer.

It's - among other uses - a shortcut for initializing collections. Learn more ...

The first brace creates a new Anonymous Class and the second set of brace creates an instance initializers like the static block.

Like others have pointed, it's not safe to use.

However, you can always use this alternative for initializing collections.

  • Java 8
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
  • Java 9
List<String> list = List.of("A", "B", "C");

This would appear to be the same as the with keyword so popular in flash and vbscript. It's a method of changing what this is and nothing more.

Related