Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does hashtable read correct values in case of collision?

I have some hashtable. For instance I have two entities like

john = { 1stname: jonh, 2ndname: johnson },
eric = { 1stname: eric, 2ndname: ericson }

Then I put them in hashtable:

ht["john"] = john;
ht["eric"] = eric;

Let's imagine there is a collision and hashtable use chaining to fix it. As a result there should be a linked list with these two entities like thisenter image description here How does hashtable understand what entity should be returned for key? Hash values are the same and it knows nothing about entities structure. For instance if I write thisvar val = ht["john"]; how does hashtable (having only key value and its hash) find out that value should be john record and not eric.

like image 731
mtkachenko Avatar asked Jan 17 '17 12:01

mtkachenko


1 Answers

I think what you are confused about is what is stored at each location in the hashtable's adjacent list. It seems like you assume that only the value is being stored. In fact, the data in each list node is a tuple (key, value).

Once you ask for ht['john'], the hashtable find the list associated with hash('john') and if the list is not empty it searches for the key 'john' in the list. If the key is found as the first element of the tuple then the value (second element of the tuple) is returned. If the key is not found, then it means that the element is not in the hashtable.

To summarize, the key hash is used to quickly identify the cell in which the element should be stored if present. Actual key equality is tested for to decide whether the key exists or not.

like image 86
George Octavian Rabanca Avatar answered Oct 11 '22 20:10

George Octavian Rabanca