1

When overriding the equals() and hashCode() methods of a class, would the following approach work?

All my logic to see if the objects are equal is done in my equals() method. The class has a static variable (we'll call it hashCodeReturn) that is set to 1.

When ever the equals method reaches logic that would return false, it adds 1 to hashCodeReturn

The hashCode() then simply returns the hashCodeReturn value

Is there any reason this would not work?

Many thanks.

3
  • What's the purpose of hashCodeReturn? Commented Jan 11, 2013 at 9:22
  • 1
    Please provide some sample code so that we can see what you mean... Commented Jan 11, 2013 at 9:24
  • I'll put the code at the bottom of the post (well, I will in 8 hours when stackoverflow lets me!) Commented Jan 11, 2013 at 9:28

2 Answers 2

10

No, it would not work.

The hash code of two objects that are the same (e.g. the same reference) should be the same. By returning the result of a static variable you'll break this contract.

The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

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

4 Comments

The static value is associated with the class, and incremented each time the equals method returns false. This means that you could get a hashcode for A, compare B and C to false, and then get a different hashcode for A (this all assumes I've understood the question correctly!)
That is correct Jeff. So the contract would not be broken as 2 equal objects would have the same hashCode (obviously I wouldn't use 1 perhaps, maybe a random number)
@JeffFoster: yes, I deleted my comment right after you added the contract of hashcode. That made your explanation precise and showed the flaw of his approach. (+1)
@Mike: The contract would be broken, see Jeffs comment under the answer.
0

Hashcode() must return same value when called upon the same object reference but when returning a static value which may be have be changed when called previously and may change because that is the variable of class which may get decremented and incremented independent of its object and that would have changed upon next calling of 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.