wood burning stoves
The moose likes Java in General and the fly likes Override equals and hashCode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Override equals and hashCode" Watch "Override equals and hashCode" New topic

Override equals and hashCode

Tom Henricksen
Ranch Hand

Joined: Mar 23, 2004
Posts: 136

I have a custom class I created and needed to override equals and hashCode.

Does this look okay?
[ December 21, 2006: Message edited by: Tom Henricksen ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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: 136

    Thank you very much for this advice. I appreciate it very much.

    Happy Holidays!

    I agree. Here's the link: http://aspose.com/file-tools
    subject: Override equals and hashCode
    It's not a secret anymore!