List colors = new ArrayList() {{
add("red");
add("yellow");
add("blue");
add("green");
}};
What is this? Some kind of secret syntax for initializing collections?
No. Look further... it's double brace initialization.
The first brace creates an inner class, like how you would instantiate a thread:
The second brace is an intializer block, a not so often used feature to initiate class instances like:Thread t = new Thread() {
public void run() {}
};
class Thingy {
int x;
{
x = 42;
}
}
Together they create an anonymous inner class with a block of code that will execute immediately. This way you can call any method of the instance you want, such as add() in the example.
Nice trick to freak out your colleagues :-). Beware though as a colleague warned me. You have to be careful since the instance is not of the reference type class but of a subclass. The result from equals() might not always be as you expect when it calls getClass() on the object.
There are other interesting Java idioms to read about too.
No comments:
Post a Comment