As HashMap
uses LinkedList
when two different keys produces a same hashCode
.But I was wondering what makes LinkedList
a better candidate here over other implementation of List
.Why not ArrayList
because ArrayList
uses Array
internally and arrays
have a faster iteration compared to a LinkedList
.
The array is used to store the hash of the key and the linked list is used to store the data and the key and other stuff. One thing to note here is that, the HashMap stores the object in the form of Entry Class. And that Entry class is in the form of a linked list.
because it means that the normal trade-off between LinkedList and ArrayList does not apply. The normal trade-off is: ArrayList uses less space, but insertion and removal of a selected element is O(N) in the worst case. LinkedList uses more space, but insertion and removal of a selected element1 is O(1) .
HashMap implements the Map interface. The List interface is implemented by both ArrayList and LinkedList.
Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i: update the pointer in member i-1 to point to the new member. set the pointer in the new member to point to member i.
Collisions in hash maps are an exception, rather than a rule. When your hash function is reasonably good, as it should be, there should be very few collisions.
If we used ArrayList
for the buckets, with most lists being empty or having exactly one element, this would be a rather big waste of resources. With array lists allocating multiple members upfront, you would end up paying forward for multiple collisions that you may not have in the future.
Moreover, removing from array lists is cheap only when the last element gets deleted. When the first one gets deleted, you end up paying for the move of all elements.
Linked lists are free from these problems. Insertion is O(1), deletion is O(1), and they use exactly as many nodes as you insert. The memory overhead of the next
/prior
links is not too big a price to pay for this convenience.
The problem with an arrayList is that you can't fast remove an element: you have to move all the elements after the one you remove.
With a linkedList, removing an element is merely changing a reference from one node to the new next one, skipping the removed one.
The difference is huge. When you want to have a list and be able to fast remove elements, don't use an arraylist, the usual choice is the linked list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With