首页 > 代码库 > Hash function
Hash function
1.the division method
h(k) = k mod m
When using the division method, we usually avoid certain values of m. For
example, m should not be a power of 2, since if m^2p, then h(k) is just the p
lowest-order bits of k.
A prime not too close to an exact power of 2 is often a good choice for m.
2.The multiplication method
The multiplication method for creating hash functions operates in two steps. First,
we multiply the key k by a constant A in the range 0 < A < 1 and extract the
fractional part of kA. Then, we multiply this value by m and take the floor of the
result. In short, the hash function is
h(k) = [m(kA mod 1)] ;
where “kA mod 1” means the fractional part of kA We tepically choose m to be a power of 2
use hashCode() to get an array index
private int hash(Key x){ return (x.hashCode() & 0x7fffffff)%M; //turn 32bit to 32bit }
use hashCode on private type
public int hashCode() { int hash = 1; hash = 31*hash + who.hashCode(); hash = 31*hash + when.hashCode(); hash = 31*hash + ((Double) amount).hashCode(); return hash; // return Objects.hash(who, when, amount); }
Hash function