I have two questions. Firstly, consider the below code.
public class Test{
private static final List<String> var = new ArrayList<String>() {{
add("A");
add("B");
System.out.println("INNER : " + var);
}};
public static void main(String... args){
System.out.println("OUTER : " + var);
}
}
When I run this code it gives me below output
INNER : null
OUTER : [A, B]
Can any one elaborate why INNER
is null and execution flow at a time when exactly "A" & "B" added to collection
?
Secondly, I made some changes in above code and modified to below one (just put add method within first bracket)
public class Test{
private static final List<String> var = new ArrayList<String>() {
public boolean add(String e) {
add("A");
add("B");
System.out.println("INNER : " + var); return true;
};
};
public static void main(String... args){
System.out.println("OUTER : "+var);
}
}
After running above code i got below result
OUTER : []
After viewing this I'm totally clueless here about what is going on. Where did INNER
go? Why is it not printing? Is it not called?
Because the initializer block of the anonymous class off
ArrayList
is executed before the instance reference of the anonymous class is assigned tovar
.The code is not executed because you never call the
add(String e)
method. If you did, it would result in aStackOverflowError
, sinceadd("A")
is a recursive call now.