1

I have encountered this code and i can't figure out why it works syntactly:

return new ArrayList<Module>() {
   {
      add(new AModule());
      add(new BModule());
      add(new CModule());
   }
   private static final long serialVersionUID = -7445460477709308589L;
 };
  1. What are the double {{ for ?
  2. How is the static final added to a class instance?
hurricane
  • 6,521
  • 2
  • 34
  • 44
Bick
  • 17,833
  • 52
  • 146
  • 251
  • 1
    http://stackoverflow.com/questions/2420389/static-initialization-blocks – firegnom Jul 23 '14 at 13:48
  • 2
    possible duplicate of [Initialization of an ArrayList in one line](http://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line) - take a look at the accepted answer – JonK Jul 23 '14 at 13:48
  • The {} define an anonymous class that extends ArrayList. The inner {} is an initialiser for the anonymous class. The serialVersionUID is an attribute of the class. – fipple Jul 23 '14 at 13:49

2 Answers2

4

It defines an anonymous class that is a subclass of ArrayList:

return new ArrayList<Module>() {
    ...
};

And this subclass contains an instance initializer block, i.e. a block of code that is executed each time an instance of this class is constructed:

{
  add(new AModule());
  add(new BModule());
  add(new CModule());
}

I would say that this is a bad practice. Defining a new class just to be able to add something to an ArrayList is useless.

Just do

List<Module> list = new ArrayList<>();
list.add(new AModule());
list.add(new BModule());
list.add(new CModule());
return list;

Or, if you use Guava:

List<Module> list = Lists.newArrayList(new AModule(), new BModule(), new CModule());

Or

List<Module> list = new ArrayList<>(Arrays.asList(new AModule(), new BModule(), new CModule()));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

That is called as anonymous inner class.

They enable you to declare and instantiate a class at the same time.

Since they are returning from there, they just created anonymously.

You are seeing those double braces because one is for class and another is for static block inside it.

They are looking alike double brace but actually

{  // class

    { // block inside the class

    }

}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307