While looking through the code I got from another developer, I came across the following piece of code.
public void myMethod()
{
final MyClass data1 = new MyClass(1,2,3);
final MyClass data2 = new MyClass(4,5,6);
// [...]
final MyClass dataN = new MyClass(M,O,P);
ArrayList<MyClass> list = new ArrayList<MyClass>()
{
{
add(data1);
add(data2);
// [...]
add(dataN);
}
};
}
In fact, I guess I know what this code does (populating list
with the defined data), but yet I'm astonished how the result is achieved.
Especially I'm wondering what the curly braces {}
mean in that case.
I know (think?) that this code is horrible and I've rewritten it, but just for the sake of curiosity I'm wondering what it exactly does.
My guess is the following:
- First pair of
{}
is an anonymous object creation - which is cast toArrayList<MyClass>
. - Second pair of
{}
is - I'm thinking of - something similiar to a static initializtion but for an object. Could that be some kind of anonymous constructor?
Can someone please give me some insight here? (Where may I find such "syntax-magic" in the java docs?)