2

Is Double Brace initialization syntax {{ ... }} really that bad when used to initialize static final constant?

To my knowledge the worst thing about using this pattern is that variable will contain reference to enclosing class, which is very bad especially in production environment. However, this does not seem to be an issue when applied to static constant.

Example:

private static final Map<String, Integer> MAP = new HashMap<String, Integer>() {{
        put("1", 1);
        put("2", 2);
    }};

Am I missing something or is it simply a matter of taste in this case?

Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27
  • 1
    The "worst" thing could also that it creates an anonymous subclass for no good reason. But please do show some actual code. – Thilo Feb 01 '20 at 14:16
  • 1
    Take a look at the discussion over at https://stackoverflow.com/q/924285/14955 Many of the things being said there apply to static context as well. – Thilo Feb 01 '20 at 14:18

0 Answers0