为什么要重写hashcode()

前两天遇到一个面试官,问我重写equals()和hashcode()的问题。

equals()方法,我的理解是,通常情况与 “==”是相同的,即判断两个对象是否相等。如果有要判断对象内容是否相等的时候,则需要重写,例如String类。

但是面试官问我是否需要重写hashcode()的时候,我的第一反应是要重写,但是无法回答为什么要重写....(我仿佛记得书上写过?)


为什么要重写hashcode()?

答:在JAVA程序运行时,无论何时多次调用一个对象的hashcode方法,都必须返回相同的int值。

Java规定:如果两个对象相同,则它们的hashcode值一定相同。如果两个对象的hashcode值相同,它们并不一定相同。

如果两个对象的equals方法返回值为ture,则hashcode方法也必须返回相同;如果equals方法返回false,则hashcode返回值也必须不同。 


这就可以解释,当重写euqlas()方法后,为什么要重写hashcode了:为了保证equals方法和hashcode方法的返回值一致。

这是在Set集合中定义的equals和hashcode()


public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractSet() {
    }

    // Comparison and hashing

   
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Set))
            return false;
        Collection<?> c = (Collection<?>) o;
        if (c.size() != size())
            return false;
        try {
            return containsAll(c);
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

   
    public int hashCode() {
        int h = 0;
        Iterator<E> i = iterator();
        while (i.hasNext()) {
            E obj = i.next();
            if (obj != null)
                h += obj.hashCode();
        }
        return h;
    }


更多细节,可以参考:

【http://blog.csdn.net/jing_bufferfly/article/details/50868266】

【http://blog.csdn.net/shiyanming1223/article/details/6893401】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值