| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

Double brace initialisation

Page history last edited by Manuel Kueblboeck 14 years, 7 months ago

This is a Java trick which involves creating an anonymous class with an initialiser block, eg.

new Object() {{
    // Initialisation stuff here
}};
 

It can enhance the readability of collection creation:

List<Integer> list = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
add(4);
add(5);
}};

 

Map<Integer, String> map = new HashMap<Integer, String>() {{
put(1, "one");
put(2, "two");
put(3, "three");
put(4, "four");
put(5, "five");
}};

But can also be useful in GUI programming:

JFrame frame = new JFrame() {{
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new JLabel("Hello, World!"));
pack();
}};

 

Be careful when using this, however, because any object created using double brace initialisation belongs to an anonymous subclass, not the original class. 

I found this gem at refactory.org.

Comments (0)

You don't have permission to comment on this page.