java arraylist.add overwriting



I tried to add 1D ArrayList into 2D ArrayList like the following code, but the output was

[34, 35, 36]

[[34, 35, 36]]

[4, 5, 6] [[4, 5, 6], [4, 5, 6]] <- the correct output would be [[34, 35, 36], [4, 5, 6]].

the previous one was overwritted, how can I solve this problem?

public static void main(String[] args) {
    
    ArrayList<Integer> a = new ArrayList<Integer>();
    ArrayList<ArrayList<Integer>> d = new ArrayList<ArrayList<Integer>>();
    
    
    a.add(34);
    a.add(35);
    a.add(36);
    d.add(a);
    System.out.println(a);
    System.out.println(d);
    a.clear();
    a.add(4);
    a.add(5);
    a.add(6);
    d.add(a);
    System.out.println(a);
    System.out.println(d);

}

Answer

You put the array list a into the list d as object, not only its content. Any changes you make to a after that will be reflected in d as well. To avoid that make a copy of a before putting it into d.



Source: stackoverflow