Câu hỏi phỏng vấn Java
Câu hỏi

What is **Double Brace i...

Câu trả lờ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:

  1. 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.

  2. 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

senior

Gợi ý câu hỏi phỏng vấn

junior

How does Garbage Collection prevent a Java application from going out of memory?

middle

What are the restrictions imposed on Java applets?

middle

Is there anything like static class in Java?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào