0

One way to deal the collision in hash tables is by chaining. Chaining store the collided items in a link list. But when a user search with a key how does hash table identify the item?

rgaut
  • 3,159
  • 5
  • 25
  • 29

3 Answers3

2

1) The key is hashed to arrive at a hash bucket.

int hashKey = key.hashCode();

2) Everything in this bucket is chained in a linked list. We can iterate it until we find one element that matches the key. For every entry in the linked list,

if (key.equals(entry.getKey()) { return entry.getValue(); }

The second step is a plain linear search.

Hashtables only work properly if these chains don't get long, so you have to size the table large enough (and choose a decently hashable key) to avoid/minimize collisions.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • So is this handled through double hashing ? – rgaut Sep 25 '14 at 06:27
  • 2
    No. It's not hashed again. It just calls `equals` on the two keys (the one you want and the one in the bucket list). Plain linear search. – Thilo Sep 25 '14 at 06:28
1

The hash table compares your key against each key in the linked list that matches the hash of your key.

  • What you are saying is called double hashing isn't it? – rgaut Sep 25 '14 at 06:27
  • No, you are not generating another hashcode for your key. Say keys k1 and k2 generate the same hashcode h1. The hashtable will have a list for hashcode h1 with both k1 and k2. – nothingtodohere Sep 25 '14 at 06:28
1

Short answer, by linearly searching the chain for the element. The hash function generates the head of the chain.

To be more precise this works in Theta(1+l) where l is the load factor, faster compared to linear normal linear search of O(n)

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52