1.对象存储在散列表中(如hashset,hashmap等)
此时hashCode方法和equals方法才有关联,百度都会有这句话“equals方法重写了hashcode方法也要重写”
个人理解为:例如在hashset中存储,而hashset的底层实现的,底层存储的数据结构是先通过hashcode方法确定index,而当table[index]已存在其它元素时,会在table[index]位置形成一个链表,再继续判断继续通过equals方法判断当前要存放的对象是否已经在链表中出现过,如果没有出现过就加入链表后。
现在有一个类重写了equals方法,且创建了两个对象,这两个对象通过equals方法比较相等(此时的设计也是认为两个对象相等,即他们只有一个可以加入hashset集合中)
但是如果Object的hashcode方法没有被重写,此时两个不同对象的hashcode肯定不相同,(但数组table[index]的位置可能是相同的,之后就是在该位置的链表中通过equals判断是否相等,这种情况下,两个对象只有一个会被加入hashset,但是大概率计算得到的index是不同的),当index不同时,两个对象都会被加入hashset中,明显和设计初衷相悖,所以需要重写hashcode方法。
//jdk1.8 Object.hashCode();为本地方法
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <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™ programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
2.没有散列表的因素存在
hashCode方法和equals方法没有关联,也可以不写,但是同时重写两个方法,代码肯定更加健壮(万一其他人不知道直接用散列表存储进行一系列的逻辑操作了呢)
3.这里贴一遍文章链接:hashCode和equals的区别