Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Override equals and hashCode

 
Tom Henricksen
Author
Ranch Hand
Posts: 144
5
Eclipse IDE jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Author
    Ranch Hand
    Posts: 144
    5
    Eclipse IDE jQuery Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you very much for this advice. I appreciate it very much.

    Happy Holidays!

    Thanks,
    Tom
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic