为什么重写equals方法需要重写hashcode方法?

SUN(ORACLE),JDK源码中这样表达:
     * <p>
     * Note that it is generally necessary to override the <tt>hashCode</tt>
     * method whenever this method is overridden, so as to maintain the
     * general contract for the <tt>hashCode</tt> method, which states
     * that equal objects must have equal hash codes. 
     *
     * @param   obj   the reference object with which to compare.
     * @return  <code>true</code> if this object is the same as the obj
     *          argument; <code>false</code> otherwise.
     * @see     #hashCode()
     * @see     java.util.Hashtable
     */
    public boolean equals(Object obj) {
	return (this == obj);
    }
重写equals方法时候重写hashcode方法的主要目的就是让Hashtable/HashSet/HashMap等集合正常工作,也就是说他们都是基于hashcode进行地址判断的,如果重写equals而不重写hashcode,对于HashMap来说存入2个相同的对象保存一个key,却对应2个值,而取的时候是无法取出值,其它的集合类也是类似,为了不至于混乱出错,所以以上集合类重写equals时候必须重写hashcode方法。是不是其它的类也是的呢?我认为不完全是,因为普通类重新hashcode意义不大,不写也不会出现编译错误,但SUN(ORACLE)官方规定,还是按照规定来吧,只其然也要知其所然。

你可能感兴趣的:(java,equals,HashCode)