Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equals() and hashCode() contract in Java

The SCJP 6 Study Guide from Bert Bates and Kathy Sierra states on page 554 (among other requirements) that x.hashCode() != y.hashCode() requires that x.equals(y) == false.

But the Javadoc for Object doesn't mention such requirement explicitly. Quote:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Should I take what Javadoc says as a material implication, such as eq -> hc? Then there would be no conflict between these two sources.

like image 846
prasopes Avatar asked Mar 04 '11 21:03

prasopes


People also ask

What is the contract between hashCode () and equals () in Java?

General contract associated with hashCode() methodIf two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects.

What is the difference between hashCode () and equals () methods?

Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.

Why equals () and hashCode () method used?

Both methods, equals() and hashcode() , are used in Hashtable , for example, to store values as key-value pairs. If we override one and not the other, there is a possibility that the Hashtable may not work as we want, if we use such object as a key.

How hashCode () and equals () methods are used in HashMap?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.


2 Answers

The two statements are equivalent.

Put simply:

  1. if two hashcodes differ, the objects are definitely different under equals.
  2. if two hashcodes are the same, we don't know. (but in many practical cases the objects will be equal).
like image 122
Mark Bolusmjak Avatar answered Oct 01 '22 18:10

Mark Bolusmjak


As z5h says, the statements are equivalent.

For logical conditions x and y, "x implies y" is the same as "!y implies !x".

"If something is a bus, it's red" is logically equivalent to "if something isn't red, it's not a bus."

This is contraposition.

Should I take what Javadoc says as a material implication, such as eq -> hc.

Yes, that's exactly what it's saying: two objects being equal under equals implies their hashcodes must be equal.

like image 28
Jon Skeet Avatar answered Oct 01 '22 18:10

Jon Skeet