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!
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With