Why java Instance initializers? [duplicate]

I use them very often, typically for creating and populating Map in one statement (rather than using an ugly static block):

private static final Map<String, String> CODES = new HashMap<String, String>() {
    {
        put("A", "Alpha");
        put("B", "Bravo");
    }
};

One interesting and useful embellishment to this is creating an unmodifiable map in one statement:

private static final Map<String, String> CODES = 
    Collections.unmodifiableMap(new HashMap<String, String>() {
    {
        put("A", "Alpha");
        put("B", "Bravo");
    }
});

Way neater than using static blocks and dealing with singular assignments to final etc.

And another tip: don’t be afraid to create methods too that simplify your instance block:

private static final Map<String, String> CODES = new HashMap<String, String>() {
    {
        put("Alpha");
        put("Bravo");
    }

    void put(String code) {
        put(code.substring(0, 1), code);
    }
};

Leave a Comment