HashMap different bucket index for a key possible?

My concern was to check how Java HashMap gets the same index for a key. Even when it's size expand from default 16 to much higher values as we keep adding Entries.

I tried to reproduce the indexing algorithm of HashMap.

int length=1<<5;
int v=6546546;
int h = new Integer(v).hashCode();
h =h^( (h >>> 20) ^ (h >>> 12));
h=h ^ h >>> 7 ^ h >>> 4;
System.out.println("index :: " + (h & (length-1)));

I ran my code for different values of "length". So for same key I am getting different index, as length of HashMap changes. What am I missing here?

My Results:

length=1<<5;
index :: 10

length=1<<15; 

index :: 7082

length=1<<30;  
index :: 6626218
Jon Skeet
people
quotationmark

You're missing the fact that every time the length changes, the entries are redistributed - they're put in the new buckets appropriately. That's why it takes a bit of time (O(N)) when the map expands - everything needs to be copied from the old buckets to the new ones.

So long as you only ever have indexes for one length at a time (not a mixture), you're fine.

people

See more on this question at Stackoverflow