Brackets in brackets in Java

What actually means the use of parentheses in brackets during initialization, for example. new list?

new ArrayList<String>() { { add("A"); } }; 

Does this mean that after creating a new reference method is called?

+6
source share
1 answer

This is a smart idiom for creating and initializing a collection.

What actually happens is that you instantiate an anonymous subclass of ArrayList , which has an instance initializer block that calls add on the list instance to populate it. The internal {...} is the instance initializer block.

A similar trick can be used to create pre-initialized maps.

+5
source

All Articles