Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How collision between different HashMap objects is avoided?

I have found that HashMaps calculate hashes for performance optimization. They use hashCode() to split up Keys into different buckets, and equals() for further comparison within those buckets.

However, I could not find an explanation of how collision between different HashMap objects is averted.

Current understanding:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Different objects can have the same hash.
  2. Thus different Map Keys can end up in the same bucket.
  3. Keys of different maps can also have the same hash.
  4. Thus Keys of independent map objects can also end up in the same bucket.

If assumptions 3 and 4 are correct, would not it be possible for different HashMaps overwrite each others Values by accident? Or retrieve a Value that belongs to a wrong Map?

How is this avoided?

e.g.

HashMap<MyKey, Value> map1 = new HashMap<>();

HashMap<MyKey, Value> map2 = new HashMap<>();

Can MyKey values of map1 and map2 end up in the same bucket?

Can map2 instead of its own values start retrieving values of map1?

>Solution :

Different HashMap objects don’t share buckets.

Your item #2 should be changed to "different map keys of the same HashMap can end up in the same bucket" and #4 is straight up wrong, as each HashMap has its own array of buckets to use that a totally independent of what any other HashMap does.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading