问题
I have a small doubt with the concept of Rehashing in HashMap.
Lets say I have a HashMap with size 8 and within that I have an Object(E1) present at index 7. So when we put multiple elements, forcing the HashMap to increase its internal Array size, which will lead to rehashing.
So my question goes, After the rehashing, will my Object(E1) be placed at 7th index or will it get a different bucket.
Appreciate useful response and references.
回答1:
The bucket your key is placed in is a function of its hashCode modulus the size of the array used to hold the HashMap (which is the number of buckets), so re-hashing can move a key to a different bucket.
回答2:
OpenJDK implementation shows that each new bucket will be re-indexed to a (potentially) different index in the new table:
void More ...transfer(Entry[] newTable) {
489 Entry[] src = table;
490 int newCapacity = newTable.length;
491 for (int j = 0; j < src.length; j++) {
492 Entry<K,V> e = src[j];
493 if (e != null) {
494 src[j] = null;
495 do {
496 Entry<K,V> next = e.next;
497 int i = indexFor(e.hash, newCapacity); // <-- new index is calculated here
498 e.next = newTable[i];
499 newTable[i] = e; // <-- and assigned
500 e = next;
501 } while (e != null);
502 }
503 }
504 }
回答3:
It will be placed at a different index. I am posting the answer to highlight the point that the term Re-Hashing doesn't represent the operation properly. It should be Re-Indexing.
Unfortunately oracle docs also has used the same terminology and called it "rehashing". But it described the process as to rebuilt the internal data structure - the array.. This array is called hash table by them, and I think that's the reason, creating the hash table newly is being called rehashing.
来源:https://stackoverflow.com/questions/29642950/rehashing-in-hashmap-in-java