为什么要重写hashcode()

来源:互联网 发布:ios10不安全网络怎么连 编辑:程序博客网 时间:2024/06/07 18:13

前两天遇到一个面试官,问我重写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】

原创粉丝点击