Next: The Integer hash function
Up: Choice of hash function
Previous: Choice of hash function
Index
In the String class, for example, the hash code h of
a string s of length n is calculated as
or, in code,
int h = 0;
for (int i = 0; i < n; i++) {
h = 31*h + s.charAt(i);
}
For example the hash code of hello uses the Unicode values of
its characters
to give the value
In general the arithmetic operations in such expressions will use
32-bit modular arithmetic ignoring overflow. For example
Integer.MAX_VALUE + 1
= Integer.MIN_VALUE
where
Integer.MAX_VALUE |
= |
|
Integer.MIN_VALUE |
= |
|
Note that, because of wraparound associated with modular arithmetic,
the hash code could be negative, or even zero. It happened to be
positive in this case because hello is a fairly short string.
Thus, for example, the hash code for helloa, which is 31
times the hash code for hello plus 97, would not be
, which is outside the range of 32-bit signed integers,
but
.
Next: The Integer hash function
Up: Choice of hash function
Previous: Choice of hash function
Index
Peter Williams
2005-06-07