-1

Why does it work? Could explain me how and why, please!

List<String> list = new ArrayList<String>() {
    {
        add("one");
        add("two");
        add("three");
    }
};

for ( String element : list )
    System.out.println(element);

1 Answers1

1

This means you created a class extending the arraylist and added a static block.

List<String> list = new ArrayList<String>(){};  // At this step you have created an instance of an anonymus class assigned to the list varibale

new ArrayList<String>() {
        {
        add("one");
        add("two");
        add("three");
        } // This is a static block inside your newly created anonymus class. 
};
Syam S
  • 8,421
  • 1
  • 26
  • 36