-1

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.

Santosh Ksl
  • 162
  • 2
  • 10
  • 2
    The loop will raise an exception. You access to an out of bound index of the array : 10. – davidxxx Feb 07 '18 at 21:14
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Savior Feb 07 '18 at 21:15
  • arrays are zero-based, should be `arr[i-1] = a` – DAle Feb 07 '18 at 21:16
  • @DAle no, the `for` loop should be a standard `for(int i = 0;i < 10; i++)`. – Kayaman Feb 07 '18 at 21:19
  • I have no idea what you're asking. – shmosel Feb 08 '18 at 03:00

1 Answers1

1

In the actual code, the loop will raise an exception as you access to an out of bound index of the array : 10.
About the printing issue in the second loop, you get a NPE because the first index of the array is not valued in your first loop : you start it to 1 but in the second loop you use a for each that iterates all indexes of the array : 0 included.
arr[0] being null, arr[0].data can only rise a NPE.

Morale : initialize your loop to 0 to fill an array :

for(int i = 0; i < 10; i++) {...}

It avoids this kind of error.

davidxxx
  • 125,838
  • 23
  • 214
  • 215