Reputation:
I am going through HashMap implementation and referring to this link: How does Java implement hash tables? I am finding that "A HashMap contains an array of buckets in order to contain its entries". So, I have few questions-
3.In case of same hashcode for a key or collision it uses linked list.How it gets(search) the reference of the second, third node etc.
Thanks in adv.
Upvotes: 0
Views: 151
Reputation: 24802
From the OpenJDK8 code source :
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
Upvotes: 1
Reputation: 77
If the hashmaps grows there is a very expensive rehash function, because the array has to grow to the next power of 2 aswell. In this case every bucket has to recalulate its index. In this case a new array is constructed. This means there is no dynamic data structure needed.
You can avoid rehashes if you create a new hashmap with a suitable capacity argument.
Upvotes: 1
Reputation: 1009
That depends on the map you make, if you make a HashMap<Integer, String>
then the buckets will be of those types, able to contain those types of objects
Because the drawbacks are worth it compared to the performance gain. Because arrays are a fixed size, a lot of checks can be skipped (i.e. does this index exist?). You can read more about that here; https://en.wikiversity.org/wiki/Java_Collections_Overview and Why not always use ArrayLists in Java, instead of plain ol' arrays?
That is explained here better than I can; What happens when a duplicate key is put into a HashMap?
Upvotes: 1