Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Brackets in Bracket in Java [duplicate]

Tags:

java

What actually means using brackets in brackets while initializing e.g. new List ?

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

Does it mean that after creating new reference method is invoking ?

like image 361
Nominalista Avatar asked Sep 29 '15 06:09

Nominalista


1 Answers

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

What is actually happening is that you are creating an instance of an anonymous subclass of ArrayList which has an instance initializer block that calls add on list instance to populate it. The inner {...} is the instance initializer block.

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

like image 142
Stephen C Avatar answered Oct 14 '22 23:10

Stephen C