Why does Java use (hash & 0x7FFFFFFF) % tab.length to decide the index of a key?

Jackson Tale picture Jackson Tale · Feb 21, 2012 · Viewed 12.8k times · Source

From the link below, I know Java uses (hash & 0x7FFFFFFF) % tab.length to decide which slot of an array to put the {key, value} in.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Hashtable.java#Hashtable.put%28java.lang.Object%2Cjava.lang.Object%29

My question is why Java first does hash & 0x7FFFFFFF? Is there any particular purpose?

Answer

sinsedrix picture sinsedrix · Feb 21, 2012

Because:

  • 0x7FFFFFFF is 0111 1111 1111 1111 1111 1111 1111 1111 : all 1 except the sign bit.

  • (hash & 0x7FFFFFFF) will result in a positive integer.

  • (hash & 0x7FFFFFFF) % tab.length will be in the range of the tab length.