JAVA基础:hashCode与equals方法

通常我们都会看到这样一段描述:重写equals方法是,必须同时重写hashCode方法。很多人都没有太过深入的了解过hashCode方法,觉得它实在太过于神秘。现在让我们一起解开hashCode的神秘面纱。
show me the code:

// 以下代码均出自于jdk(1.8)中

  /**
     *  ···
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java&trade; programming language.)
     * ···
     */
    public native int hashCode();
    /**
     * ···
     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * ···
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

总结:

  • Object类的hashCode方法将对象在内存中的地址转化为整数返回
  • 如果两个对象的根据equals方法相等,则hashCode的返回值也必须一致
  • 在JAVA程序执行期间,在同一对象上多次调用hashCode方法,只要不修改它在equals方法比较中使用的信息,必须始终返回相同的整数
  • 同一应用程序的不同执行,hashCode不必保持一致
  • 两个对象的equals方法返回不相等时,不要求hashCode方法返回不同的整数。但是编程人员应该意识到为不同的对象返回不同的hashCode将会提高哈希表的性能

拓展:
当我们需要提升equals方法的性能时,可以先通过hashCode(高性能)进行判断,再通过复杂、性能稍差的equals逻辑进行比较,可以大大提升性能。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。