This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Override equals and hashCode Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Override equals and hashCode" Watch "Override equals and hashCode" New topic
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
    
  13

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
     
    I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
     
    subject: Override equals and hashCode
     
    Similar Threads
    Properly overriding equals and hashCode
    Object destroyed automatically in 20 seconds from Map
    hash code for enum and long field combined
    HashCode and Equals
    hashCode() & equals() method test