Why does Hashmap
internally use a LinkedList
instead of an Arraylist
when two objects are placed in the same bucket in the hash table?
LinkedList should be used where modifications to a collection are frequent like addition/deletion operations. LinkedList is much faster as compare to ArrayList in such cases. In case of read-only collections or collections which are rarely modified, ArrayList is suitable.
From a memory allocation point of view, linked lists are more efficient than arrays. Unlike arrays, the size for a linked list is not pre-defined, allowing the linked list to increase or decrease in size as the program runs.
HashMap implements the Map interface. The List interface is implemented by both ArrayList and LinkedList.
ArrayList is faster in storing and accessing data. LinkedList is faster in manipulation of data.
Why does
HashMap
internally use sLinkedList
instead of anArraylist
, when two objects are placed into the same bucket in the hash table?
Actually, it doesn't use either (!).
It actually uses a singly linked list implemented by chaining the hash table entries. (By contrast, a LinkedList
is doubly linked, and it requires a separate Node
object for each element in the list.)
So why am I nitpicking here? Because it is actually important ... 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)
.
However, in the case of the private singly linked list formed by chaining together HashMap
entry nodes, the space overhead is one reference (same as ArrayList
), the cost of inserting a node is O(1)
(same as LinkedList
), and the cost of removing a selected node is also O(1)
(same as LinkedList
).
Relying solely on "big O" for this analysis is dubious, but when you look at the actual code, it is clear that what HashMap
does beat ArrayList
on performance for deletion and insertion, and is comparable for lookup. (This ignores memory locality effects.) And it also uses less memory for the chaining than either ArrayList
or LinkedList
was used ... considering that there are already internal entry objects to hold the key / value pairs.
But it gets even more complicated. In Java 8, they overhauled the HashMap
internal data structures. In the current implementation, once a hash chain exceeds a certain length threshold, the implementation switches to using a binary tree representation if the key type implements Comparable
.
1 - That is the insertion / deletion is O(1)
if you have found the insertion / removal point. For example, if you are using the insert and remove methods on a LinkedList
object's ListIterator
.
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