Usage of Double Brace Initialization in Java
This post will discuss the usage of the double brace initialization technique in Java.
We can use a double brace for creating and initializing Java objects in a single expression. This creates an anonymous inner class with just an instance initializer in it. This post provides an overview of some of the common usages of double brace initialization:
1. Initialize an object in Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.Arrays; class Employee { private String name; private int id; public void setName(String name) { this.name = name; } public void setAge(int id) { this.id = id; } // getters @Override public String toString() { return Arrays.asList(name, String.valueOf(id)).toString(); } } // Initialize an object in Java class Main { public static void main(String[] args) { // Anonymous class Employee person = new Employee() {{ // Initializer block setName("Aditya"); setAge(27); }}; System.out.println(person); } } |
Output:
[Aditya, 27]
2. Initialize set in Java
|
1 2 3 4 5 |
Set<Integer> set = new HashSet<Integer>() {{ add(1); add(2); add(3); }}; |
3. Initialize list in Java
|
1 2 3 4 5 |
List<String> list = new ArrayList<String>() {{ add("C"); add("C++"); add("Java"); }}; |
4. Initialize map in Java
|
1 2 3 4 5 |
Map<String, String> map = new HashMap<String, String>() {{ put("USA", "Washington"); put("UK", "London"); put("India", "New Delhi"); }}; |
5. Join two lists in Java
|
1 2 3 4 5 6 7 8 |
// Generic method to join two lists in Java public static<T> List<T> merge(List<T> a, List<T> b) { return new ArrayList<T>() {{ addAll(a); addAll(b); }}; } |
6. Join two sets in Java
|
1 2 3 4 5 6 7 8 |
// Generic method to join two sets in Java public static<T> Set<T> mergeSets(Set<T> a, Set<T> b) { return new HashSet<T>() {{ addAll(a); addAll(b); }}; } |
Note that we should best avoid this technique as it costs an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects, which may cause problems with serialization or memory leaks.
That’s all about the usage of Double Brace Initialization in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)