KSHiTiJ KSHiTiJ - 1 year ago 74
Java Question

SCJP HashCode() And Equals() Confusion

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.

Answer Source

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()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download