繁体   English   中英

Java:如何检查 Hashmap 中是否存在密钥

[英]Java : How to check if a key is exists in a Hashmap

我已经定义了一个 hashmap 类型:

HashMap<Position, Double> list = new HashMap<>();

其中 Position 是 class 具有两个属性 x 和 y。

我想验证 position 是否已经在列表中,我试过这个:

public void addToList(Position p, double somme) {
    if (this.list.containsKey(p)) {
        this.list.replace(p, this.list.get(p) + somme);//add the old value somme 
    } else {
        this.list.put(p, somme);
    }
}

我认为我应该更具体并验证 x any y 的值,而不是检查密钥是否存在,因为每次检查都无法检测到存在的 position。

如何检查 position 是否在列表中?

您应该覆盖 Position object 的equalshashCode方法,以便 x 和 y 具有相同值的两个元素相等。

@Override
public boolean equals(Object obj) { 
    if (obj == this) {
        return true;
    }
    if (obj == null || obj.getClass() != this.getClass()) {
        return false;
    }

    Position otherPos = (Position) obj;
    return x == otherPos.x
            && y == otherPos.y;
}

@Override
public int hashCode() {
    return Objects.hash(x, y);
}

根据 x 和 y 属性,在 Position class 中实现等于和哈希码。 Hashmap 使用后者来查找要在其中检查密钥的存储桶 - 仅使用 equals 是行不通的。

请注意,hashcode 和 equals 必须一致,因为两个相等的对象必须具有相同的 hashcode。

正如提到的另一个答案,基于 Position 实现这些和 containsKey 方法将按您的预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM