Sorry, I have corrected the logic a but , my ask was different . However it got clarified after referring to Java pass by reference, which create another reference variable while pushing it to stack or list or array.
public class Node {
public int data;
public Node left;
public Node right;
}
public static void main(String[] args) {
Node[] arr = new Node[10];
Stack<Node> s = new Stack<Node>();
List<Node> ls = new ArrayList<Node>();
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i <10; i++) {
Node a = new Node();
a.data = i;
s.push(a); -> another reference to a is created and pushed
ls.add(a); -> another reference to a is created and pushed
arr[i] = a; -> -> another reference to a is created and pushed
a = null; // referencing it to null, makes one of the references
//to null
}
for(Node i : s) {
System.out.println("result"+i.data); // prints 1-9
}
for(Node i : ls) {
System.out.println("result"+i.data); // prints 1-9
}
System.out.println(arr.length); // prints 10
for(Node i : arr) {
System.out.println("result2"+i.data); // prints 1-9
}
}
What is the stack's push() or list's add() is making the object retain its value? even after I set its value to null. Is it something like a variable copy and Thanks.