君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理

SUN(ORACLE),JDK源码中这样表达: 

Java代码  收藏代码
  1.  * <p>  
  2.  * Note that it is generally necessary to override the <tt>hashCode</tt>  
  3.  * method whenever this method is overridden, so as to maintain the  
  4.  * general contract for the <tt>hashCode</tt> method, which states  
  5.  * that equal objects must have equal hash codes.   
  6.  *  
  7.  * @param   obj   the reference object with which to compare.  
  8.  * @return  <code>true</code> if this object is the same as the obj  
  9.  *          argument; <code>false</code> otherwise.  
  10.  * @see     #hashCode()  
  11.  * @see     java.util.Hashtable  
  12.  */  
  13. public boolean equals(Object obj) {  
  14. urn (this == obj);  
  15. }  

重写equals方法时候重写hashcode方法的主要目的就是让Hashtable/HashSet/HashMap等集合正常工作,也就是说他们都是基于hashcode进行地址判断的,如果重写equals而不重写hashcode,对于HashMap来说存入2个相同的对象保存一个key,却对应2个值,而取的时候是无法取出值,其它的集合类也是类似,为了不至于混乱出错,所以以上集合类重写equals时候必须重写hashcode方法。是不是其它的类也是的呢?我认为不完全是,因为普通类重新hashcode意义不大,不写也不会出现编译错误,但SUN(ORACLE)官方规定,还是按照规定来吧,只其然也要知其所然。

posted on 2013-07-21 02:01  刺猬的温驯  阅读(113)  评论(0)    收藏  举报