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?
3
  • 1
    stackoverflow.com/questions/2420389/… Commented Jul 23, 2014 at 13:48
  • 2
    possible duplicate of Initialization of an ArrayList in one line - take a look at the accepted answer Commented Jul 23, 2014 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. Commented Jul 23, 2014 at 13:49

2 Answers 2

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()));
Sign up to request clarification or add additional context in comments.

1 Comment

or List<Module> list = Arrays.asList(new AModule(), new BModule(), new CModule()); ;-)
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

    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.