gpt4 book ai didi

java - 在我调用一个明显不相关的方法后,我的 ArrayList 被清空

转载 作者:行者123 更新时间:2023-11-29 06:59:03 25 4
gpt4 key购买 nike

这是我的方法:

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;
}

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

我怀疑我可能误解了有关 ArrayList 声明或 retainAll 方法的某些内容。我不明白为什么在我调用“retainAll”方法后“this.coordinates”被清空。

感谢大家的帮助!

最佳答案

此行复制ArrayList

testCoordinates = this.coordinates;

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

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

testCoordinates = this.coordinates;

用这个:

testCoordinates = new ArrayList<int[]>(this.coordinates);

关于java - 在我调用一个明显不相关的方法后,我的 ArrayList 被清空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com