What is Double Brace initialization in Java?
What is Double Brace initialization in Java?
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:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.