Reputation: 2253
I'm trying to understand the inner implementation of HashMap in Java. I have a confusion with the 'createEntry' method.
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
it creates an entry object 'e' and then it puts it to another entry object and stores it into the bucket[bucketindex] and it also stores the key and value. I am not able to understand the purpose of creation of the Entry object 'e' here. Could someone please explain.
Regards
Upvotes: 1
Views: 202
Reputation: 279970
It gets the previous entry in the bucket (even if it is null
). It then creates a new entry, setting its next
entry to that previous one retrieved. It then sets the new entry to the same index in the bucket.
So say you had 3 element in hash
0: [null]
1: [some entry]
2: [null]
And you had to add to index 1
0: [null]
1: [new entry] -> [some entry]
2: [null]
Similarly, adding to index 0
0: [newer entry] -> [null]
1: [new entry] -> [some entry]
2: [null]
Upvotes: 6