- 论坛徽章:
- 0
|
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. |
|