The double brace initialization {{ ... }}
is another way for initializing a collection objects in Java. It is offer a simple syntax for initializing a collection object.
package org.kodejava.lang;
import java.util.ArrayList;
import java.util.List;
public class DoubleBraceInitialization {
public static void main(String[] args) {
// Creates a list of colors and add three colors of
// Red, Green and Blue.
List<String> colors1 = new ArrayList<>();
colors1.add("Red");
colors1.add("Green");
colors1.add("Blue");
for (String color : colors1) {
System.out.println("Color = " + color);
}
// Creates another list of colors and add three colors
// using the double brace initialization.
List<String> colors2 = new ArrayList<>() {{
add("Red");
add("Green");
add("Blue");
}};
for (String color : colors2) {
System.out.println("Color = " + color);
}
}
}
What’s actually happened is: the first brace creates an anonymous inner class and the second brace is an initializer block. Due to the need for creating an inner class the use of double brace initialization is considered to be slower.
Because of this performance issue it’s better not to use this technique for your production code, but using it in your unit testing can make your test looks simpler.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024