2

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:

  • Whenever two objects are the same in terms of equals() method, their hash code must be the same
  • Whenever two objects are not the same in terms of equals() method, we have no guarantee for theid hashcode(), i.e. it might be the same, it might be different
  • when we use HashMap.put(key, value) HashMap compares objects by their equal() method. If the two keys are equal() then the new value is overriden
  • If two kays have the same hashcode then collision occurs and Java deals with it
  • However if two keys are equal then the new value is overriden, BUT it also implies that the hashCode() must be the same, so collision must happen, which is a contradiction with the previous?

Can someone please clarify these steps for me?

sammy333
  • 1,384
  • 6
  • 21
  • 39
  • http://stackoverflow.com/questions/11559954/internals-of-how-the-hashmap-put-and-get-methods-work-basic-logic-only – cy3er Jul 24 '14 at 09:38
  • What you wrote was correct. It may be a matter of interpretation: When two objects are equal (and thus have the same hash code) it's not really a "collision that has to be dealt with". The objects are equal, so there is no bucket size that has to be increased or so... – Marco13 Jul 24 '14 at 09:40

2 Answers2

4

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523