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.