Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 867
Jackson Tale Avatar asked Feb 21 '12 15:02

Jackson Tale


People also ask

What is the purpose of using hash?

Hashing uses functions or algorithms to map object data to a representative integer value. A hash can then be used to narrow down searches when locating these items on that object data map. For example, in hash tables, developers store data -- perhaps a customer record -- in the form of key and value pairs.

Does Java have hash?

Java provides multiple ways to implement hashing. Some of the most popular ways are using the HashMap and HashSet classes. Both the HashMap and HashSet classes use hashing algorithms to store and retrieve data.


2 Answers

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.

like image 93
sinsedrix Avatar answered Sep 28 '22 07:09

sinsedrix


Because -1 % 10 == -1 which you certainly don't want for indexing into an array. Forcing the sign bit to 0 avoids this problem.

like image 33
Voo Avatar answered Sep 28 '22 07:09

Voo