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?
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.
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.
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.
Because -1 % 10 == -1
which you certainly don't want for indexing into an array. Forcing the sign bit to 0 avoids this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With