Capacity and indexFor in Java Hashmap

Viewed 1382

While going through the source code of Java HashMap, we can see the first bucket for a key is determined with the method as below:

 static int indexFor(int h, int length) { //h = hash of key 
     return h & (length-1);               //length = capacity of array at 
 }                                        //         current time

As per my understanding if initial size is 16 (length-1 = 15 = 1111) and if the generated hash of a key k1 is 108378 (1 10100111 01011010), then indexFor() method will return 10 (1010).

Now, say after some addition the capacity has changed to 32. Now if I want to search for key k1 (with hash 108378), it will again go to check the bucket with same indexFor() method. Now the h & (length-1) code snippet will return 26. (108378 & 31).

My question is how will this get method will find the correct bucket, if the table get resized?

3 Answers
Related