Double brace initialization

Create the List and MAP using an anonymous subclass and initialize

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainClass {

public static void main(String[] args) {

List numbers = new ArrayList() {{add(1);add(2);}};
System.out.println(numbers);

Map codes = new HashMap() {{put(“1”, “one”);put(“2”, “two”);}};
System.out.println(codes);

List<String> list=new ArrayList<String>(){{add(“Java”);add(“Php”);add(“C”);add(“C++”);}};
System.out.println(list);
}
}

OUTPUT

[1, 2]
{1=one, 2=two}
[Java, Php, C, C++]

It gets the name for the double {{ }} present in the expression. In the above example we are doing 2 things:
1. Create an anonymous inner class which extends ArrayList/HashMap.
2. Provide an instance initialization block which invokes the add/put method and adds the required elements

Note- The advantage we have with this approach is that we can combine creation and initialization into an expression and pass around into different methods.

Leave a comment