When did add() method add object in collection

RBS :

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?

Andreas :
  1. Because the initializer block of the anonymous class off ArrayList is executed before the instance reference of the anonymous class is assigned to var.

  2. The code is not executed because you never call the add(String e) method. If you did, it would result in a StackOverflowError, since add("A") is a recursive call now.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36084&siteId=1