What is **Double Brace i...
What is **Double Brace i...
Double Brace Initialization in Java refers to a technique that combines the creation of an anonymous inner class and an instance initializer block to initialize objects, particularly collections, in a single expression. This approach is often used to create and populate collections like lists, sets, or maps in a more concise way compared to traditional methods.
Here's how it works:
Anonymous Inner Class: The first brace {
signifies the creation of an anonymous inner class that extends a particular class, usually a collection class like HashSet
or ArrayList
. This inner class inherits methods from its parent class.
Instance Initializer Block: The second brace {
introduces an instance initializer block within the anonymous inner class. This block is executed whenever an instance of the anonymous inner class is created, allowing for the initialization of the object.
For example, traditionally, to create and populate a Set<String>
you would do something like this:
Set<String> set = new HashSet<>();
set.add("one");
set.add("two");
set.add("three");
Using Double Brace Initialization, the same can be achieved with less code:
Set<String> set = new HashSet<String>() {{
add("one");
add("two");
add("three");
}};
While Double Brace Initialization can make the code more concise, it has several disadvantages:
Obscurity: It is not a widely known or used technique, which can make the code harder to understand for other developers.
Extra Class: It creates an additional anonymous inner clas...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào