0

I am studying how HashMap works inside and can not understand this method:

void addEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);

Why object e gets the address (or what happens here?) of table[bucketIndex] and then this table[bucketIndex] get the new Entry(hash, key, value, e)? What is the reason, why didn't just use what is below?

Entry<K,V> e = new Entry<K,V>(hash, key, value)
table[bucketIndex] = e;
  • 2
    What version of JDK is this? – Ilya Lysenko Mar 03 '20 at 22:00
  • Forgetting things specific to Java for a moment, do you understand the abstract data structure known as a "hashtable" or "hashmap"? If not, you may want to look at [this question](https://stackoverflow.com/q/730620/17300) and some of its answers. – Stephen P Mar 03 '20 at 22:12

1 Answers1

2

Because there could be collisions in the HashMap (i.e. different keys which produces the same bucketIndex). If they did what you suggests, in the case of a collision, the last inserted element would delete the previous ones in the case of a collision, possibly in a virtually unpredictable manner.

The Entry is implemented as some sort of linked list, so it is actually a bit misnamed and is in fact a node of linked list of entries. This is the reason why e is passed as the last parameter of Entry constructor.

Creating a new Entry that refers to the previous one (the e) and adding it in the same place where the e was is the operation of inserting a new node in the beggining of the linked list, and works even if e was null (i.e. there was no collision at all and the created Entry is the first one with the given bucketIndex).