Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap uses LinkedList internally

Tags:

java

hashmap

public V get(Object key) {
if (key == null)
    return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}

What I knew is, if you want to get a object from HashMap, first of all it searches the hash bucket based on hashcode/hash value and then iterates through the LinkedList in that hashbucket(suppose the diff objects have same hash code, thus in the same hash bucket).

But after looking at the code above, I am not able to understand when it iterates through the LinekedList(and where is the LinkedList)

like image 857
lowLatency Avatar asked Apr 02 '13 15:04

lowLatency


People also ask

Does HashMap uses linked list internally?

HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value.

Is HashMap a linked list?

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.

How linked HashMap works internally?

How LinkedHashMap Work Internally? Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and insertion are faster. Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this parameter is the key to the data.

Is HashMap an array of linked list?

Looking at the source code of HashMap tells us that it's implemented as an array of Entries: transient Entry[] table; Each Entry has a field next , so they create a single linked list structure: static class Entry<K,V> implements Map.


1 Answers

The bucket is the linked list, effectively. The table array is an array of Entry elements, and each Entry is a linked list, in that each entry knows about the next one in the list, until you reach the end when the next reference is null. The for loop you've shown iterates over the linked list.

It's not a LinkedList as in a java.util.LinkedList - it's a separate (simpler) implementation just for the map.

like image 149
Jon Skeet Avatar answered Oct 17 '22 01:10

Jon Skeet