If I have a HashMap/HashTable and I insert the Key:c
Value:14
[0] -> NULL
[1] -> NULL
[2] -> NULL
[3] -> NULL
[4] -> NULL
[5] -> NULL
[6] -> NULL
[7] -> NULL
[8] -> NULL
[9] -> (c/14) -> NULL
[0] -> NULL
[1] -> NULL
[2] -> NULL
[3] -> NULL
[4] -> NULL
[5] -> NULL
Let's say I insert the Key:z
Value:6
and the hash and modulus have it land on index 9
.
My question is: do I insert at the end of the singly linkedlist (meaning (c/14) -> (z/6) -> NULL
) or at the front of the LinkedList.
If I insert the new collisions at the front of each bucket, then I don't need to loop over the entire LinkedList chain. This makes insertion O(1)
, since no matter how big the bucket is, I don't need to loop over all the elements.
If I insert the new collisions at the end of each bucket, I must loop over the entire singly list until I reach the last element. Then I append the last element.
No matter which one I choose, retrieval from the List will be the same. I might still need to loop over all nodes in a bucket. Unless you would argue that it's more likely for the user to call get()
on a key
that was added earlier.
Despite this, I see all examples and implementations of HashTable's and HashMap's add the element at the end of the bucket. Why?