|
|
Graphically:
|
|
|
Reason:
|
|
|
|
|
static int hashCode(long x)
{
int p1, p2;
p1 = (int) x; // lower 32 bits
p2 = (int) (x >> 32); // upper 32 bits
return(p1 + p2);
}
|
static int hashCode(double d)
{
int p1, p2;
long x;
x = Double.doubleToRawLongBits(d); // Use the bits as a long....
p1 = (int) x; // lower 32 bits
p2 = (int) (x >> 32); // upper 32 bits
return(p1 + p2);
}
|
|
Example:
|
|
|
Example:
|
|
|
(In the test program, I used a = 100 to show the effect of the polynomial computation)
Example:
|
public static int hashCode(String s)
{
int i;
int r = 0;
char c;
for (i = 0; i < s.length(); i++)
{
c = s.charAt(i); // process next character
r = (int) c + (r << 1); // Left shift 1 = multiply by 2
}
return(r);
}
|
public static int hashCode(String s)
{
int i;
int r = 0;
char c;
for (i = 0; i < s.length(); i++)
{
c = s.charAt(i); // process next character
r = (int) c + ((r << 1) + r << 0)); // (2 + 1)r
}
return(r);
}
|
Faster (but approximate) implementation:
public static int hashCode(String s)
{
int i;
int r = 0;
char c;
for (i = 0; i < s.length(); i++)
{
c = s.charAt(i); // process next character
r = (int) c + ((r << 1) | r << 0)); // Bit-wise OR os faster than an addition
}
return(r);
}
|
Hash index = hashCode % N
|
|
|
Hash index = ( (a × hashCode + b) % p ) % N
|
Note:
|
|
|
This is not so when you use a non-prime number
any key
/ | \
/ | \ (will result in some hash code)
/ | \
hash code x = 0 1 2 3 4 5 6 7 8 9 10 11 12 ...
| compress
V
(3×x + 1) % 12) % 10 = 1 4 7 0 1 4 7 0 1 4 7 0 1 ...
| | | | | |
+------------+ +------------+ +------------+
repeat repeat repeat
|
Notice that:
|
any key
/ | \
/ | \ (will result in some hash code)
/ | \
hash code: k = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15...
| compress
V
(3×k + 1) % 13) % 10 = 1 4 7 0 0 3 6 9 2 2 5 8 1 1 4 7 ...
| |
+------------------------------------------------+
repeat
|
Notice that:
|