Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does one arraylist change when a copy of it is modified

Tags:

java

Its probably a very simple one but its' still confusing me!

import java.util.ArrayList;

public class Sample {
    ArrayList<Integer> i = new ArrayList<>();
    ArrayList<Integer> j = new ArrayList<>();

    /**
     * @param args
     */
    public static void main(String[] args) {
        new Sample().go();
    }

    private void go() {

        i.add(1);
        i.add(2);
        i.add(3);

        j=i;

        i.remove(0);


        System.out.println(i + "asd" + j);
    }

}

I tried to print it :

[2, 3]asd[2, 3]

Why does j change when i changes? Does not happen with primitives though!

like image 688
Mercenary Avatar asked Oct 24 '13 17:10

Mercenary


1 Answers

The statement j=i; assigns the reference j to be the same reference as i. Now both i and j refer to the same ArrayList object. The removal of the 0th index is simply visible through both references.

If you would like the removal of an item in i not to affect the list from j, then create a copy of the list, instead of assigning the references:

j = new ArrayList<Integer>(i);

(It's a shallow copy, so the lists still refer to the same elements.)

like image 75
rgettman Avatar answered Nov 13 '22 22:11

rgettman