You can use it with an anonymous class:
new MyClass() { { // do something extra on construction (after the constructor executes) } }
I find this particularly useful for initializing βsearchβ maps (i.e. fixed content) in place:
Map<String, String> map = new HashMap<String, String>() { { put("foo", "bar"); put("one", "two");
FYI, this is sometimes (weakly) called "double-bracket initialization" when in fact it just uses an initializer block.
Although such an anonymous class is technically a subclass, the beauty of this is shown when comparing using this method with the more traditional one when creating an unmodifiable map:
Compare this simple single-line layer that combines data and purpose:
private static final Map<String, String> map = Collections.unmodifiableMap( new HashMap<String, String>() {{ put("foo", "bar"); put("one", "two");
With this mess, which should create a separate object because of final , allowing only one assignment:
private static final Map<String, String> map; static { Map<String, String> tempMap = new HashMap<String, String>(); tempMap.put("foo", "bar"); tempMap.put("one", "two");
Also note that with the mess version these two statements should not be contiguous, so it becomes less obvious what the contents of an unmodifiable map are.
Bohemian
source share