-1

The implementation of equals() and hashCode() should follow these rules.

  1. If o1.equals(o2), then o1.hashCode() == o2.hashCode() should always be true.
  2. If o1.hashCode() == o2.hashCode() is true, it doesn’t mean that o1.equals(o2) will be true.

If o1.hashCode() == o2.hashCode() is true . i know, that If two objects are equals then these two objects should return same hash code. if two objects hash code is a same, why does it not mean that o1.equals(o2)?

ernest_k
  • 39,584
  • 5
  • 45
  • 86
  • 2
    For the same reason that all people with the name "Rezo" are not you. – Kayaman Dec 11 '19 at 14:43
  • The correct statement is "not all people with the name Rezo are you". We have empirical evidence that at least of them is. ;-) –  Dec 12 '19 at 03:48

4 Answers4

6

Consider Long. There are 2^64 possible values for this type. hashCode returns an int, which only has 2^32 possible values.

For identity hash code (availble from System.identityHashCode), objects move around in memory on many modern JVM implementations. There is no reasonable way of keeping track of which hash codes are still in use. Even with a (thread-safe) counter, after 2^32 allocations there will need to be some kind of reuse.

Tom Hawtin - tackline
  • 139,906
  • 30
  • 206
  • 293
0

The purpose of a hash function (the clue is in the name) is to return values distributed uniformly in a range for different objects. Not to return a different value for each object.

This means a hash function normally has collisions. Though ideally their number should be as small as possible.

Andres
  • 9,722
  • 4
  • 37
  • 57
0

Imagine a hash algorithm (and not necessarily a good one) as the following.

  1. Take the last 4 digits our some assigned ID.

  2. Imagine two ID's of 12341234 and 67281234.

The hashCodes are identical but the id's and hence what they identify may not be.

WJS
  • 22,083
  • 3
  • 14
  • 32
0

It's a bit like:

If John and James are twins, then they must belong to the same mother

Which (I'm sure you agree) does not mean that

If John and James belong to the same mother, then they must be twins

Where "having the same mother" is having the same hash code, and "being twins" is being equal.

For the rest, I suggest you read through the first answer of this question What is the use of hashCode in Java?

ernest_k
  • 39,584
  • 5
  • 45
  • 86