Menu

The equals and hashCode contract in Java: Failure modes and the TreeSet twist
📰

The equals and hashCode contract in Java: Failure modes and the TreeSet twist

DEV Community: java·srinivas reddy gouru·about 2 hours ago
#dYuSTQMR
#devtojava#devto#dev#equals#hashcode
Reading 0:00
15s threshold

1. The one idea to hold onto

Forget the formal wording for a moment and hold this picture instead.

Think of an object as a person's full name, like "Srinivas Reddy". Think of

hashCode() as that person's initials, "SR": a cheap little summary you can

compute from the full name in a second. And think of equals() as the slow,

careful check: do the two full names actually match, letter for letter?

With that picture, the two clauses of the contract stop being rules and become

common sense.

Clause one: equal objects must have equal hash codes. If two records are the

same person, their initials must come out the same. "Srinivas Reddy" gives you

"SR" every single time. It would be absurd for the identical name to produce

"SR" on one form and "TK" on another. So when the full thing is equal, any

summary derived from it is forced to be equal too. That is just what "summary of

the same thing" means.

Clause two: equal hash codes do NOT force the objects to be equal. Flip it

around.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.