免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1391 | 回复: 2
打印 上一主题 下一主题

equals() & hashCode() [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-08-23 16:54 |只看该作者 |倒序浏览
Books say always that hashCode() should be overridden whenever you override equals().

Why?
Would equals() invoke hashCode() as JVM performed equals()?

论坛徽章:
0
2 [报告]
发表于 2003-08-23 23:53 |只看该作者

equals() & hashCode()

ftp://cinc.3322.org/pub/doc/java/effective_java/effective_java.pdf
Chapter 2

&

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

&

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()

论坛徽章:
0
3 [报告]
发表于 2003-08-24 02:20 |只看该作者

equals() & hashCode()

cnic, thanks a lot !!

I think I found the answer about it from the book, called effective java.

Overriding the hashCode() is not necessary absoulately if I just want to compare the content of both instances simply.

I ever tested it and just overrode equals() only for a class I created.
Then I found that equals() could worked without problem.

The following was quoted from the Effective java....


If you simply test fields for equality, it's not hard to adhere to the equals contract. If
you are overly aggressive in searching for equivalence, it's easy to get into trouble. It
is generally a bad idea to take any form of aliasing into account. For example, the
File class shouldn't attempt to equate symbolic links referring to the same file.


A common source of bugs is the failure to override the hashCode method. You must
override hashCode in every class that overrides equals. Failure to do so will result in a
violation of the general contract for Object.hashCode, which will prevent your class from
functioning properly in conjunction with all hash-based collections, including HashMap,
HashSet, and Hashtable.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP