...
Code Block | ||
---|---|---|
| ||
// method imod() gives non-negative result
private int SIZE = 16;
public int[] hash = new int[SIZE];
private int imod(int i, int j) {
return (i == Integer.MIN_VALUE) ? 0 :
(i < 0) ? ((-i) % j) : (i % j);
}
public int lookup(int hashKey) {
return hash[imod(hashKey, size)];
}
|
Note that Integer.MIN_VALUE
is a psecial corner case, because it can not be negated. (Mathematically, - Integer.MIN_VALUE == 1 + Integer.MAX_VALUE
.)
Compliant Solution
Alternatively, an explicit range check must be performed on the numerator at every susceptible point as demonstrated in this compliant solution.
Code Block | ||
---|---|---|
| ||
public int lookup(int hashKey) { if (hashKey < 0) return hash[(-hashKey) % sizeSIZE]; return hash[hashKey % sizeSIZE]; } |
Note that providing a well-documented imod
method is a better choice as it improves readability and makes it clear that its sole purpose is to return positive values when required and not to "fix" the unintuitive behavior of the remainder operator, as defined by the specification.
...