In the following code the getEntriesNotWorking
method reports a compile-time error:
public class DoubleBracketInitializerTest {
class Container {}
class Entry {
Container container;
public Entry(Container container) {
this.container = container;
}
}
class DetailedContainer extends Container {
List<Entry> getEntriesNotWorking() {
return new ArrayList<Entry>() {{
add(new Entry(this)); // compile-time error mentioned below
}};
}
List<Entry> getEntriesWorking() {
return Arrays.asList(new Entry(this));
}
}
}
Error:
The constructor DoubleBracketInitializerTest.Entry(new ArrayList(){}) is undefined
While the getEntriesWorking()
method is compiling correctly. The constructor is clearly there since a DetailedContailer
is a subclass of Contailer
.
What is the difference between those two methods, that makes the code invalid? How can I make the double bracket initializer work for this class hierarchy?