Do you know Java: Double Brace Initialization


Double brace initialization is a very comfortable way to add values to a collection or pairs to a map instance instead of having multiple statements next to each other.

One of the most popular languages, though Java is full of interesting parts that look wierd or unusual at first glance. In the sequence I call Do you know Java, I would like to present these less known or unexplained parts of the languages.

The usual way

Usually to initialize a collection or a map we do:

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("apple", 2);
map.put("melon", 5);

Double Braces

Double brace initialization brings the opportunity to do this at the so-called same time.

Map<String, Integer> map = new HashMap<String, Integer>() {{
  put("apple", 2);
  put("melon", 5);
}};

How it works

Inner braces belong to the init block of the anonymous class derived from HashMap. Its put method is called on the super of our map object.

Double brace initialization is a form of adding elements to a collection at initilization time.

Code can be found: https://github.com/torokmark/do-you-know-java