0

Can I use the implementation of hashCode() to implement my equals() in Java? Or is it a bad practice?

Eg.,

public int hashCode()
{
    // some computation based on the internal states
}

public equals(Object o) 
{
     return o instanceof ThisClass ? hashCode() == o.hashCode() : false;
}
9
  • 1
    It won't be good enough. You might get duplicate int values that don't necessarily mean that the objects are equal. Commented Mar 6, 2014 at 20:38
  • stackoverflow.com/questions/2132334/… Commented Mar 6, 2014 at 20:39
  • No. en.wikipedia.org/wiki/Pigeonhole_principle Commented Mar 6, 2014 at 20:39
  • But if I get two equal objects with different hashcodes, that would be equally bad, woudln't it? Commented Mar 6, 2014 at 20:39
  • 1
    Yes, that would violate the contract of equals/hashCode. What is allowed is for there to be non-equal objects with equal hashcodes. Your equals/hashCode methods have to be consistent with each other - based on the same information, basically. Commented Mar 6, 2014 at 20:40

2 Answers 2

7

This is bad practice. Just because the hashCodes are equal DOES NOT mean the objects are equal.

If memberwise comparison is too expensive, then you can use the hashCode as an initial check to tell you if the objects are not equal. You still need to do the member comparison if the hashCodes match though.

Sign up to request clarification or add additional context in comments.

1 Comment

In other words, you can use hashCode as the first check in your equals method, and return false if they hashcodes are not the same, but if the hashcodes are equal, you still need to do the other checks.
0

Whether it works depends on the hashCode function. A hashCode implementation is required to map equal objects to the same value. It is desirable, as far as possible, to map unequal objects to different values, but that is not required and is often impossible. Many classes have more possible unequal object values than there are int values.

If your hashCode function does map any pair of objects that are not equal to two different hashCode values then two objects of the class are equal if, and only if, they have the same hashCode and it could be used in equals.

Do not count on other classes having distinct hashCode values for unequal objects. For example, there are more distinct String values than int values, so String's hashCode has to map unequal objects to the same hashCode.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.