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?
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'.
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);
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.
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.
Because the initializer block of the anonymous class off ArrayList
is executed before the instance reference of the anonymous class is assigned to var
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With