I am wondering why does Hashtable avoid using negative hashcode ?
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
Where (hash & 0x7FFFFFFF) makes the signed bit to be 0 to positive, but why couldn’t we treat the signed 32 bit integer as unsigned ? or even use the modular tricks to make it become positive. For example,
public static long int_mod(int hashcode, int tab_length){
return (hashcode % tab_length + tab_length) % tab_length;
}
The value has to be between
0andtab.length - 1because it is used as an index into an internal array (tabin this case) storing the values (and overflow elements). Therefore, it cannot be negative.I assume
(hash & 0x7FFFFFFF) % tab.lengthis used in preference of(hashcode % tab.length + tab.length) % tab.lengthbecause it is faster without unduly increasing the chance of collisions, but you would have to find a design document or talk to the original developers to know for sure.