0

I want to exercise the "Clear" utility of java. However, when I am using clear even after adding the sublist value to the super list, the values are somehow overwritten to null. What is the reason for this behavior?

    public static void main(String [] args)
    {
        List<Integer> abc= new LinkedList<>();
        List<List<Integer>> abc2= new LinkedList<>();
        int j=2;
        while(j > 0) {
            for (int i = 1; i < 4; i++) {
                abc.add(i);
            }
            //abc.stream().forEach(e-> System.out.println(e));
            abc2.add(abc);
            abc.clear();
            //abc= new LinkedList<>();
            j--;
        }

        abc2.stream().forEach(e-> System.out.println("," + e));
    }
}

Why I am getting below result:

,[],[]

instead of:

,[1, 2, 3] ,[1, 2, 3]

Ria Sachdeva
  • 113
  • 6
  • 1
    `abc2` contains the same list, `abc`, multiple times. `abc` is empty because you clear it. – khelwood Aug 30 '20 at 00:51
  • I added it to the main list before clearing it. Shouldn't it value to retain the abc2 list? – Ria Sachdeva Aug 30 '20 at 00:56
  • 1
    No, the list inside `abc2` is the *same list* as `abc`. So if you clear it, it's empty. – khelwood Aug 30 '20 at 00:57
  • 1
    Simply put, you're passing by reference `abc`. That's because Java passes by reference objects. So when you clear `abc`, it gets cleared from `abc2`. – Marwan N Aug 30 '20 at 01:11

0 Answers0