gpt4 book ai didi

java - 为什么答案是 2 :2:1:1 when we are removing all elements of a SET

转载 作者:行者123 更新时间:2023-12-02 04:36:54 24 4
gpt4 key购买 nike

当我们向 Set 中添加元素时,它会丢弃重复的值。当我们删除 Set k1 和 k2 中的元素时。最终大小仍为 1。代码答案为 2:2:1:1。

class KeyMaster {
public int i;

public KeyMaster(int i) {
this.i = i;
}

public boolean equals(Object o) {
return i == ((KeyMaster) o).i;
}

public int hashCode() {
return i;
}
}


public class MapIt {

public static void main(String[] args) {
Set<KeyMaster> set = new HashSet<KeyMaster>();
KeyMaster k1 = new KeyMaster(1);
KeyMaster k2 = new KeyMaster(2);
set.add(k1);
set.add(k1);
set.add(k2);
set.add(k2);

System.out.print(set.size() + ":");
k2.i = 1;

System.out.print(set.size() + ":");
set.remove(k1);

System.out.print(set.size() + ":");
set.remove(k2);

System.out.print(set.size());
}
}

最佳答案

这是因为HashSet中的Key不是不可变的,所以当你改变k2的某个字段值时,这个字段值改变了,但对象保持不变,所以当你想要从集合中删除 k2,它找不到 k2,因为您的对象已更改。

为了更好地理解它,让 k1 去测试一下:

class MapIt {
public static void main(String[] args) {
Set<KeyMaster> set = new HashSet<KeyMaster>();
KeyMaster k2 = new KeyMaster(2);
set.add(k2);
set.add(k2);

System.out.print(set.size() + ":");
k2.i = 3;
System.out.print(set.size() + ":");
set.remove(k2);

System.out.println(set.size());
}
}

关于java - 为什么答案是 2 :2:1:1 when we are removing all elements of a SET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30635306/

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