Search code examples
javahashmapnew-operatordata-retrievalhash-collision

How to retrieve values after a hash collision


I have read in many places that after a hash collision in Java it is internally using a linked list/tree, based on the number of hash collisions.Till this is fine,

But how to retrieve back the expected value using the 'key'


Solution

  • It just iterates the linked list stored in that bucket and checks the elements using equals which has no collisions.

    The running time for that is linear, but only linear in the amount of items stored in that specific bucket, so it is okay as long as the buckets are kept balanaced well enough.

    Look at this illustration (source):

    enter image description here

    So the implementation will make sure that a get operation, even if it has collisions, gives back the correct result in the end.


    Note that Javas HashSet and HashMap are not a pure hashtable like illustrated. They will switch to a red-black tree internally after a certain threshold.