A tip for initializing static constants using double brackets in JAVA
- 2020-04-01 03:21:39
- OfStack
This seems like an unknown language skill. I've seen that the average person who writes Java initializes static constants is
public static final Map<String, String> DATA = new TreeMap<String, String>();
static
{
DATA.put("a", "A");
//blah blah blah
}
Using the static block of the class to initialize DATA, there is another way to write it:
public static final Map<String, String> DATA = new TreeMap<String, String>()
{{
this.put("a", "A");
//blah blah blah
}};
This actually takes advantage of the nature of anonymous classes. The inner {is used as a constructor for anonymous subclasses, so you can insert the initialization code directly.