This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: What is Java double brace initialization?

So what’s bad about double parenthesis initialization

Answer 1: Double parenthesis initialization creates an anonymous class derived from the specified class (outer parentheses) and provides an initialization block within the class (inner parentheses). For example

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

Note that initialization with double parentheses creates anonymous inner classes. It is worth mentioning that you create a class with an implicit this pointer that only wants to surround other external classes. While this is usually not a problem, in some cases (such as serialization or garbage collection) it can cause problems for the program to run.

Answer 2:

In addition to the syntax being very unusual and not something we really use (which is, of course, sometimes really nice), you unnecessarily create two important problems in your application

1. You create too many anonymous classes during program execution.

Each time you initialize with double curly braces, a new class is created. Take this 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");
        }});
    }});
}};
Copy the code

This will give you the following classes

Test$1$1$1.class
Test$1$1$2.class
Test$1$1.class
Test$1.class
Test.class
Copy the code

2, you may be causing a memory leak!

If you take the code above and return the map from a method, the callers of that method may no doubt hold resources that cannot be reclaimed. Consider the following example:

public class ReallyHeavyObject {

    // Just to illustrate...
    private int[] tonsOfValues;
    private Resource[] tonsOfResources;

    // This method almost does nothing
    public Map quickHarmlessMethod(a) {
        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");
                }});
            }});
        }};

        returnsource; }}Copy the code

The Map returned will now contain a reference to the closed instance, ReallyHeavyObject.