gpt4 book ai didi

java - 检查和删除 Java HashMap 中的元素

转载 作者:行者123 更新时间:2023-12-03 02:55:35 26 4
gpt4 key购买 nike

我正在尝试使用 Java 中的 HashMap 检查并删除元素。它的键是我创建的称为 ClusterKey 的类型,它的值是我创建的称为 ClusterValue 的类型。

以下是导致问题的代码:

ClusterKey ck = new ClusterKey(Long.parseLong(split[0].split("=")[1]), 
Integer.parseInt(split[1].split("ey")[1]));
if (arg == 0) keys.put(ck, new ClusterValue(index, false));
if (arg == 1) {
if (keys.containsKey(ck)) {
index = keys.get(ck).messageNo;
keys.remove(ck);
}
keys.put(ck, new ClusterValue(index, true));
}

问题是,即使 ClusterKey 与现有 ClusterKey 相同, containsKey() 和 remove() 似乎也不会将其识别为相等。我在 ClusterKey 类中实现了 equals() 来覆盖 Java 的 equals() 方法,如下所示:

class ClusterKey {
long firstKey;
int secondKey;
public ClusterKey(long firstKey, int secondKey) {
this.firstKey = firstKey;
this.secondKey = secondKey;
} public boolean equals(Object otherKey) {
return this.firstKey == ((ClusterKey) otherKey).firstKey && this.secondKey == ((ClusterKey) otherKey).secondKey;
}
}

所以,我很困惑。非常感谢您的帮助。

问候,丽贝卡

更新:感谢您对我的代码的建议和反馈。我通过将 hashCode() 添加到 ClusterKey 来解决该问题,如下所示:

    } public boolean equals(Object otherKey) {
return this.firstKey == ((ClusterKey) otherKey).firstKey && this.secondKey == ((ClusterKey) otherKey).secondKey;
} public int hashCode() {
return (int) firstKey + secondKey;
}

最佳答案

要使任何启用哈希的数据结构(例如 HashMapHashSet)正常工作,除了equals() 方法。原因是散列码用于标识要在其中放置元素(在插入期间)或搜索(在查找期间使用 equals())的存储桶。

如果您不重写 hashCode(),则使用 Object#hashCode() 的默认实现,即使对于您认为等效的对象,它也会返回不同的值(equals() 方法返回 true)。

这就是为什么你的

 hashMap.containsKey(ClusterKey key)

尽管 key 已经存在,但调用仍失败。因为哈希码与 HashMap 不匹配,所以它永远不会在正确的存储桶中查找键。因此,您的 equals() 永远不会在这里被调用。

关于java - 检查和删除 Java HashMap 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17684341/

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