理解 equals,hashcode

本文讲解了在Java中覆盖equals方法时为何同时需要覆盖hashcode方法的重要性。文章强调了这一步骤对于保持对象一致性及提升基于散列集合性能的关键作用,并提供了具体的代码示例。

Effective Java:第九条:覆盖equals时总要覆盖hashcode.


如果不这样做的话,会违反Objcet.hashCode的通用约定,从而导致该类无法结合所有基于散列的集合一起工作。这样的集合包括HashMap,HashSet,HashTable。


下面是Object的约定规范:

  1. 在应用程序执行期间,只要equals方法所用到的信息没有修改,那个对同一个对象多次调用,hashCode方法都必须始终如一的返回同一个整数。在同一个程序的多次执行过程中,每次执行所返回的整数可以不一致。
  2. 如果两个对象根据equals(object)方法比较是相等的,那么调用这两个对象的任意一个对象的hashCode方法都必须产生同样的整数值。
  3.  如果两个对象根据equals(object)方法比较是不相等的,那么调用这两个对象的任意一个对象的hashCode方法,则不一定要产生不同的整数值。但是程序员应该知道,给不相等的对象产生不同的hashcode,有可能提高散列表的性能。
Object hascode:=========

    /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hashtables such as those provided by
     * <code>java.util.Hashtable</code>.
     * <p>
     * The general contract of <code>hashCode</code> is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the <tt>hashCode</tt> method
     *     must consistently return the same integer, provided no information
     *     used in <tt>equals</tt> 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 <tt>equals(Object)</tt>
     *     method, then calling the <code>hashCode</code> 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 <tt>hashCode</tt> 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 hashtables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class <tt>Object</tt> 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<font size="-2"><sup>TM</sup></font> programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.util.Hashtable
     */
    public native int hashCode();


exmaple code :=========
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值