Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange syntax in ArrayList declaration in java [duplicate]

Recently, I stumbled upon the following java syntax:

ArrayList<String> nodes = new ArrayList<String>(){{add("n1");add("n2");}};

At first, I thought that it is a syntax error, but to my surprise, the code gave no compilation or runtime error.

I have the following questions:

  • Is there a standard definition and documentation for such declaration in Java?
  • What happens when this code is compiled?

Please point me towards relevant literature.

like image 811
Bhoot Avatar asked Apr 30 '15 12:04

Bhoot


People also ask

How do you find duplicate numbers in an ArrayList?

Using Iterator Get the ArrayList with duplicate values. Create another ArrayList. Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method. The second ArrayList contains the elements with duplicates removed.

Which is the preferred way to declare a variable of type ArrayList in Java?

The general syntax of this method is:ArrayList<data_type> list_name = new ArrayList<>(); For Example, you can create a generic ArrayList of type String using the following statement. ArrayList<String> arraylist = new ArrayList<>(); This will create an empty ArrayList named 'arraylist' of type String.


1 Answers

This creates an anonymous class with a custom initializer (see Initializing Instance Members):

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{
    // whatever code is needed for initialization goes here
}

It's convient when you want a list with members already in it, but produces more code when compiled because the anonymous class is actually compiled to a (global) class different that extends ArrayList.

I've recently read this post which is relevant to the matter:

The first point to note is that the Java runtime has no understanding of inner classes at all. Whether the inner class is named or anonymous, a smoke-and-mirrors procedure is used to convert the inner class to a global class. If the class has a name, then the compiler generates class files whose names have the format [outer]$[inner] — $ is a legal identifier in Java. For inner classes, the generated class files are simply numbered. So when the Thread example at the start of this article is compiled, we end up with a class file called Test$1.class. The number '1' indicates that this is the first anonymous class defined within the class Test.

like image 132
Reut Sharabani Avatar answered Oct 05 '22 19:10

Reut Sharabani