开发者

What does the {{ syntax on ArrayList initializer really do

I have recently found what appears to me to be a new syntax for statically initializing an ArrayList:

new ArrayList() {{ add("first"); add("second"); }};

My question is, what is really happening there? Is that a shortcut for defining a static block (I thought it would need the static keyword)? Or just a way to define a default constructor? Something else? What version of Java did this become valid?

An explanation plus a link to further reading would be greatly appreciated.

edit: My test class for showing whether initializer block executes before or after the constructor is below. Results show that initializer blocks execute before the other constructor code:

import org.junit.Test;

public class InitializerBlockTest {
    class InitializerTest {
        {
        System.out.println("Running initalizer block");
        }

        public InitializerTest() {
            System.out.println("Running default constructor");
        }
    }

    class SubClass extends InitializerTest {
      {
        System.out.println("Running subclass Initializer block");
      }
开发者_开发技巧
      public SubClass()  {
        System.out.println("Running subclass constructor");
      }
    }

    @Test
    public void testIt() {
        new SubClass();
    }
}

Output:

Running initalizer block
Running default constructor
Running subclass Initializer block
Running subclass constructor


You are creating a new anonymous subclass of ArrayList, with an instance initializer which calls add() twice.

It's the same as:

class MyList extends ArrayList
{

{ // This is an instance initializer; the code is invoked before the constructor.
add("first"); 
add("second");
}

public MyList() {
    super();
    // I believe initializers run here, but I have never specifically tested this
    }
}

...

List list=new MyList();

Note that, personally, I do not advise it as an idiom, since it will lead to class-file explosion.


It is an initializer block for instance variables.

From Oracle's documentation:

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{

    // whatever code is needed for initialization goes here
}

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

See: http://download.oracle.com/javase/tutorial/java/javaOO/initial.html


When you write new ArrayList() { } you are creating an anonymous subclass of ArrayList. The { } as in the innermost brackets in your code denote an initializer block and is actually copied into every constructor.

EDIT: You guys sure answer fast!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜