Explain the term “Double Brace Initialisation” in Java?
Double Brace Initialization is a technique in Java that allows you to create and initialize collections (like List
, Set
, or Map
) in a more concise and readable way. It involves using an anonymous inner class to create an instance of a collection and then immediately populating it with elements.
Here's how it works:
{}
creates an anonymous inner class that extends the collection class (e.g., ArrayList
, HashSet
, etc.).{}
is used to define an instance initializer block, where you can add elements to the collection.Here’s an example of using Double Brace Initialization with a List
:
import java.util.ArrayList;
import java.util.List;
public class DoubleBraceInitializationExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("Apple");
add("Banana");
add("Cherry");
}};
System.out.println(list);
}
}
new ArrayList<String>()
creates an instance of ArrayList
.{{ ... }}
block is an instance initializer that allows you to add elements to the list right after its creation.add
method is called within the initializer block to populate the list with "Apple", "Banana", and "Cherry".Double Brace Initialization is a useful technique for quickly initializing collections in Java, but it should be used judiciously, considering the potential downsides related to performance and readability.