What’s wrong with Double Brace initialization in Java?

Technology CommunityCategory: JavaWhat’s wrong with Double Brace initialization in Java?
VietMX Staff asked 3 years ago

Using Double Brace initialization is not ideal because:

  1. You’re creating way too many anonymous classes. For example:
Map source = new HashMap(){{
    put("firstName", "John");
    put("lastName", "Smith");
    put("organizations", new HashMap(){{
        put("0", new HashMap(){{
            put("id", "1234");
        }});
        put("abc", new HashMap(){{
            put("id", "5678");
        }});
    }});
}};

… will produce these classes:

Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class

That’s quite a bit of overhead for your classloader – for nothing! 2. You’re potentially creating a memory leak. If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected.