在我调用一个看似无关紧要的方法后,我的ArrayList被清空了

Mag*_*nus 1 java arraylist

这是我的方法:

public boolean checkIfFriend(Coin coin){
    ArrayList <int []> testCoordinates = new ArrayList <int[]>();
    testCoordinates = this.coordinates; //I copy my ArrayList <Coin> "coordinates" into another ArrayList, "testCoordinates".
    testCoordinates.retainAll(coin.getCoordinates()); //I remove all elements from "testCoordinates" that do not exist in the ArrayList supplied as argument.
    if (testCoordinates.size() > 1){ //On this line, "this.coordinates" has been emptied for all elements. Why?
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

在我调用"retainAll"方法之后,"this.coordinates"中有0个元素,而之前有29个元素.

我怀疑我可能误解了有关ArrayList声明或retainAll方法的内容.在我称之为"retainAll"方法之后,我不明白为什么"this.coordinates"被清空了.

谢谢大家的帮助!

rge*_*man 5

该行并没有做的一个副本ArrayList.

testCoordinates = this.coordinates;
Run Code Online (Sandbox Code Playgroud)

它指定testCoordinates引用相同的对象this.coordinates.有两个变量引用同一个对象,因此对任一引用的操作都会影响同一个对象.因此,清空ArrayListvia retainAll会影响唯一的ArrayList对象,并且通过对它的引用都可以看到更改.

要制作副本,您必须创建一个新对象.替换这个:

testCoordinates = this.coordinates;
Run Code Online (Sandbox Code Playgroud)

有了这个:

testCoordinates = new ArrayList<int[]>(this.coordinates);
Run Code Online (Sandbox Code Playgroud)