There is a test task with not the only answer:

What are the contract rules between hashCode () and equals ()?

1) If two objects return different hashcode () values, they cannot be equal
2) If two objects return the same hashCode () values, then they are equal
3) If two objects are not equal, then their hashCode () is necessarily different
4) If two objects are equal, then they should return the same hashCode () value

Do I understand correctly that, in accordance with the rules of the contract, only answer 4 is correct?

* If objects are equal according to the results of the equals method, then their hashcode should be the same.

** If objects are not equal according to the results of the equals method, then their hashcode can be either the same or different. However, for better performance, it is better that different objects return different codes.

  • And what does not suit one? - Alexey Ten

3 answers 3

Consider the simplest example of hashing.

x%2: 2%2 = 0; 4%2 = 0; 

in this case, the hash is the same, but the objects are not equal.

  1. x = 2 always returns 0 - true
  2. in the first and second case, the hashes are the same - not true
  3. see rule 2 - not true
  4. see rule 1 - right
  • How does "x = 2 always return 0" , does it mean that the first item is correct? - Regent
  • Because the same object always returns the same hash, if the hash is different, then the object is not equal to the compared one - Komdosh
  • I do not see the connection between "the same object should return the same hash" and "if two objects return different hashes, they are not equal." Here we must start from the first rule in question (because if A -> B , then !B -> !A ), and not from the fact that "if the object has not changed, then it must continue to return the same hash." - Regent
  • I do not understand what the problem is? Same objects cannot have a different hash. - Komdosh
  • About the investigation also did not understand what was it for? Identical. - Komdosh

Referring to the official source: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode ()

The general contract of hashCode is:

It is a method for you to use it. This integer need not remain the same.

If you want to get the same number of objects, you need to make it the same way.

It is not required according to the method, then it’s not necessary. However, it would be possible to improve the performance of hash tables.

From the second contract it can be judged that the correct answer is 4, and 1 is only a consequence of it.

    If the hash codes are equal, this does not necessarily guarantee that the objects are the same.

    One hundred percent, if the hash codes are different, then the objects are different.

    From this it follows that 4 and 1 is true.