1

In SCJP Book there is one Table

enter image description here

I am confuse at Last Row. If x.hashCode()! = y.hasCode() than why is ut "Required" That x.equals(y) == false.

Because from my understanding if HashCodes are different than there will be different buckets and finding Object from it will not create Problem than why "x.equals(y) == false" required?

Lets Assume That x.hashCode()! = y.hashCode(). And x.equals(y) == true.

Does it make any difference when I retrieving Or Adding object from Or To Map OR Set.?

Any Example Will Be Appreciated.

Ram Ghadiyaram
  • 28,239
  • 13
  • 95
  • 121
MRX
  • 1,611
  • 8
  • 33
  • 55

2 Answers2

1

This is for when you are implementing a custom hashCode and equals methods for your own class, it's a contract you need to respect in order to implement hashing and object equality tests in Java. They mention that in the book because it is possible, in your own implementation to violate those contracts in your own custom hashCode and equals methods

The condition you are talking about is a direct result of x.equals(y) == true implies x.hashCode() == y.hashCode() (first row in your table)

(P implies Q) is the same thing as (not Q implies not P), P being x.equals(y) == true from your first row in that textbook table, and Q being x.hashCode() == y.hashCode()

bakkal
  • 54,350
  • 12
  • 131
  • 107
0

hash codes are meant to speed up searching. if you had a.equals(b) == true and a.hashCode() != b.hashCode() then containers that use hashing would not find some results that containers without hashing would find, among other problems.

also the last row is the contrapositive of the first row.

programmerjake
  • 1,794
  • 11
  • 15
  • "containers that use hashing would not find some results". I have program that is running fine with above scenario. But i am also agree that i have to follow CONTRACT. – MRX Aug 27 '14 at 11:05
  • 1
    your program would work fine only for some implementations of hash tables. for example, if the hash table cached the last accessed element then if `a.equals(b) && a.hashCode() != b.hashCode()` then if the last-accessed element is a and you search for b then it will return a instead of b. – programmerjake Aug 27 '14 at 11:10
  • also, a container without hashing would return a and b but a non-caching hash table would return only the one with the same hash. – programmerjake Aug 27 '14 at 11:14