哈希码和等于 [英] Hashcode and equals

查看:121
本文介绍了哈希码和等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

等于 hashCode 方法必须一致,这意味着当两个对象根据<$ c相等时$ c>等于方法他们的 hashCode 方法应该返回相同的哈希值。

equals and hashCode method must be consistent, which means that when two objects are equal according to equals method their hashCode method should return the same hash value.

如果我们不覆盖hashCode()方法,Java将返回唯一的哈希码。

Java returns a unique hash code if we do not override the hashCode() method.

class HashValue {

    int x;

    public boolean equals(Object oo) {
        // if(oo instanceof Hashvalue) uncommenting ths gives error.dunno why?
        // :|
        HashValue hh = (HashValue) oo;

        if (this.x == hh.x)
            return true;
        else
            return false;
    }

    HashValue() {
        x = 11;
    }

}

class Hashing {
    public static void main(String args[]) {
        HashValue hv = new HashValue();
        HashValue hv2 = new HashValue();

        System.out.println(hv.hashCode());
        System.out.println(hv2.hashCode());

        if (hv.equals(hv2))
            System.out.println("EQUAL");
        else
            System.out.println("NOT EQUAL");
    }
}

为什么取消注释该行会出现编译错误?

Why does uncommenting the line gives compilation error?

如果对象具有不相等的哈希码,为什么它们显示相等,即使默认哈希码不同?

If the objects have unequal hash codes, why are they shown equal even though the default hashcode varies?

推荐答案

平等仅由方法equals()决定。方法hashCode()用于其他情况,例如Map或Set。在实际调用equals(效率)之前,它有点像先决条件或提示。因此假设如果2个对象相等(即equals()返回true),则它们的hashCodes()必须返回相同的值。

Equality is only determined by method equals(). And method hashCode() is used in other situations, like by Map or Set. It is somewhat like a pre-condition or hint before actually calling equals (for efficiency). So it is assumed that if 2 objects are equal (that is, equals() returns true), then their hashCodes() must return the same value.

所以在你的代码,2个对象是相等的,只要你的overriden equals()返回true,无论hashCode()做什么。在比较相等性时,根本不调用hashCode()。

So in your code, 2 objects are equal, as long as your overriden equals() returns true, no matter what hashCode() does. hashCode() is not called at all when comparing for equality.

这个问题有关于equals()和hashCode()之间关系的更深入的信息。

This question has more in-depth information regarding to the relationship between equals() and hashCode().

这篇关于哈希码和等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆