Hash Tables(similar to tables in general) provide a subset of the dynamic set operations. Usually, a set of keys are mapped with some values based on certain relations. However, there might be situations when different keys map to the same position provided by the Hash function, which leads to a collision.
One of the ways to overcome this situation is Hash Table Chaining.
The chaining approach to resolve collisions deals with it by going ahead and putting all the keys that map to a slot in that slot but representing them as a linked list.
Hash Table chaining in Java is possible with both, Singly Linked List and Doubly Linked List. Though the implementation is same, the only difference is that Doubly Linked List allows two-way traversal i.e., the node contains a pointer to the next as well as the previous node. Thus, the complexity of insertion and deletion at a known position reduces to O(1) as compared to the Singly Linked List (O(n)).
In Singly Linked List : g -> e -> e -> k -> s Here, each node contains a pointer to the next node only. In Doubly Linked List : g <-> e <-> e <-> k <-> s Each node contains pointer to the next as well as previous node.
- Insertion: To insert, a key is simply hashed to get the position in the table (the list where this new key has to be inserted), and then insert the key at the head of the doubly linked list using the standard linked list procedures (given in the code).
- Deletion: Just go through the list that the key maps to through the hash function and delete the key from that list using the standard linked list procedures (given in the code).
Below is the implementation of the above approach:
At 0: 80 At 1: 36 At 2: 47 At 3: 23 At 4: 99 At 0: 80 At 1: 36 At 2: 92 47 At 3: 23 At 4: 49 99 At 0: 80 At 1: 36 At 2: 92 47 At 3: 23 At 4: 49 At 0: At 1: At 2: At 3: At 4: true
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.