Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...