4

While looking through the code I got from another developer, I came across the following piece of code.

public void myMethod()
{
    final MyClass data1 = new MyClass(1,2,3);
    final MyClass data2 = new MyClass(4,5,6);
    // [...]
    final MyClass dataN = new MyClass(M,O,P);

    ArrayList<MyClass> list = new ArrayList<MyClass>()
    {
        {
            add(data1);
            add(data2);
            // [...]
            add(dataN);
        }
    };
}

In fact, I guess I know what this code does (populating list with the defined data), but yet I'm astonished how the result is achieved. Especially I'm wondering what the curly braces {} mean in that case.

I know (think?) that this code is horrible and I've rewritten it, but just for the sake of curiosity I'm wondering what it exactly does.

My guess is the following:

  • First pair of {} is an anonymous object creation - which is cast to ArrayList<MyClass>.
  • Second pair of {} is - I'm thinking of - something similiar to a static initializtion but for an object. Could that be some kind of anonymous constructor?

Can someone please give me some insight here? (Where may I find such "syntax-magic" in the java docs?)

Briareos386
  • 1,927
  • 18
  • 34
  • Right. Copy/paste/edit error from originating source :) Thanks for pointing that out. – Briareos386 Feb 21 '13 at 12:29
  • `{}` are braces or curly braces, not parentheses `()` https://en.wikipedia.org/wiki/Bracket – Steve Kuo Feb 21 '13 at 16:10
  • @SteveKuo Thanks for clarifying. As a german native speaker I wasn't aware of this, as in german everything is a "klammer" -- good to see english is more distinct :) – Briareos386 Feb 21 '13 at 19:38

5 Answers5

3

By first paranthesis, you are creating an annonymous inner, sub class of super class ArrayList. The second parenthesis is for instance initialization for the instances of your annonymous inner class. Have a look on this Doc for more details. There is a good explanation in this blog about instance initialization blocks

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
2
ArrayList<MyClass> list = new ArrayList<MyClass>{     //anonymous of subclass
  {     //non-static initializer block
      System.out.prinln("...");
  }
};

First of {} after new ArrayList<MyClass> which creates a new anonymous of subclass ArrayList, since ArrayList is not final class you can do it.

Second pair of {} is a non-static block or instance block inside the new sub class.


If you try Integer int1 = new Integer(10){}; this will not work because an anonymous class cannot subclass the final class Integer.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

This code won't work there is a parentheses missing (or a semicolon, but that would result in something quite different.)

final MyClass data1 = new MyClass(1,2,3);
final MyClass data2 = new MyClass(4,5,6);
// [...]
final MyClass dataN = new MyClass(M,O,P);

ArrayList<MyClass> list = new ArrayList<MyClass>()//here
{
    {
        add(data1);
        add(data2);
        // [...]
        add(dataN);
    }
};

And the first { means you create a new Class that extends ArrayList. The next { means an anonymous block, simply groups your code. EDIT: Since this is outside a function, it will be called when the object is created.

John Smith
  • 2,282
  • 1
  • 14
  • 22
1

This code creates an instance of an anonymous sub-class of ArrayList (the first pair of {}). This is relative question: How are Anonymous (inner) classes used in Java?

The nested block is an instance initialiser block (see http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html). This means that when the instance is created, this code will be executed before the constructor (any constructor) is executed.

   {
        add(data1);
        add(data2);
        // [...]
        add(dataN);
    }
Community
  • 1
  • 1
yiannis
  • 1,421
  • 12
  • 21
0
 {
        {
            add(data1);
            add(data2);
            // [...]
            add(dataN);
        }
 };

This is the instance block, so after creating the object of the ArrayList (list) , this piece of code will be executed. At each line the add() method will be invoked and the data will be inserted into the ArrayList
This is equivalent to say

ArrayList<MyClass> list = new ArrayList<MyClass>();
list.add(data1);
list.add(data2);
// [...]
list.add(dataN);

As mentioned by others, doc will explain the importance of instance block.
First the static instance block is called, then the instance block and finally the constructor. The static instance block is called only once, whereas instance block and constructors are invoked whenever a new object is created.

asifsid88
  • 4,631
  • 20
  • 30