Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When did add() method add object in collection

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?

like image 966
RBS Avatar asked Oct 07 '18 14:10

RBS


People also ask

What is the return type of add () method used to add elements in collection?

Java Collection add() method The add() method of Java Collection Interface inserts the specified element in this Collection. It returns a Boolean value 'true', if it succeeds to insert the element in the specified collection else it returns 'false'.

How do you add an Object to a collection in java?

Adding an element to a Collection is done via the add() method. Here is an example of adding an element to a Java Collection : String anElement = "an element"; Collection collection = new HashSet(); boolean didCollectionChange = collection. add(anElement);

What is the use of add method in java?

The add() method of Set in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function return False if the element is already present in the Set.

Can we create Object of collection?

Collection is not a concrete Object class it is just a interface, you have to create any collection concrete class that implements Collection interface like HashSet, ArrayList etc. Show activity on this post. you should specify type of collection.


1 Answers

  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.

like image 119
Andreas Avatar answered Sep 26 '22 08:09

Andreas