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:
- Different objects can have the same hash.
- Thus different Map Keys can end up in the same bucket.
- Keys of different maps can also have the same hash.
- 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?