| Author |
Override equals and hashCode
|
Tom Henricksen
Ranch Hand
Joined: Mar 23, 2004
Posts: 135
|
|
I have a custom class I created and needed to override equals and hashCode. Does this look okay? Thanks, Tom [ December 21, 2006: Message edited by: Tom Henricksen ]
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
1) Why are there two nested sets of "if (machine.getComplexId().equals(this.getComplexId()))"? 2)Most equals() implementations start with "if (this == obj) return true;" as an optimization for a common case. 3) This is actually not OK, at least in theory. The hashCode method uses two different members to compute the hashCode(), but equals() uses only one; that means that it's theoretically possible for two Machines to be equal, but have different hashCode()s. Perhaps this is related to #1 -- maybe one of those nested conditions is supposed to refer to the other member.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Edwin Dalorzo
Ranch Hand
Joined: Dec 31, 2004
Posts: 961
|
|
My comments on equals: The same attributes you take into account in equals() you must take into account in hashCode(). However in your hashCode() you use machineTypeId, but you did not in you equals() method. There is not need to check for the object being null. Instanceof operator will return false if the object is null. Test first for object equality (same instance) and avoid further complications in the algorithm. My comments on hashCode: You can use the members hashCode, but always test for nullability first. I hope that helps! [ December 21, 2006: Message edited by: Edwin Dalorzo ]
|
 |
Tom Henricksen
Ranch Hand
Joined: Mar 23, 2004
Posts: 135
|
|
Thank you very much for this advice. I appreciate it very much. Happy Holidays! Thanks, Tom
|
 |
 |
|
|
subject: Override equals and hashCode
|
|
|