PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How collision between different HashMap objects is avoided?

 September 20, 2022     hash-collision, hashmap, java     No comments   

Issue

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:

  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.



Answered By - Joachim Sauer
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing