sammy333
sammy333

Reputation: 1445

Confusion with hashmap in Java?

I've read all the posts in the topic and I still have confusion on the following: when overriden and collision can happen? From what I'v read I see:

Can someone please clarify these steps for me?

Upvotes: 2

Views: 204

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your point #3 comes too soon: HashMap compares for equality only when the hashCode is the same.

HashMap checks hash code first to determine the placement of the object in a bucket. The regular HashMap keeps only items with identical hash codes (modulo a certain number) in the same bucket, and checks equality only for objects within the same bucket.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234635

Think of a hashmap as a set of pigeon holes. Each pigeon hole can contain more than one object.

The hashCode() return is used to select the pigeon hole which either contains or would contain that object.

The equals() is used as the criterion to identify a specific object (e.g. for replacement).

The aim of hashCode() is to disperse typical objects uniformly across the pigeon holes. Once a particular pigeon hole has been identified as possibly containing an object then all objects in that particular group have to be examined. That operation is expensive since equals() needs to be called.

Upvotes: 4

Related Questions