Chinaunix

标题: equals() & hashCode() [打印本页]

作者: jimhongchen    时间: 2003-08-23 16:54
标题: equals() & hashCode()
Books say always that hashCode() should be overridden whenever you override equals().

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


作者: cinc    时间: 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()
作者: jimhongchen    时间: 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.




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2