...
This noncompliant code example uses the integer hashKey
as an index into the hash
array. The A negative hash key input could be negative, producing produces a negative result from the remainder operator . Consequently, causing the lookup
function will throw a ()
method to throw java.lang.ArrayIndexOutOfBoundsException
.
...
This compliant solution calls a the imod()
method that always returns a positive remainder that is always positive.
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) { int temp = i % j; return (temp < 0) ? -temp : temp; // unary - will succeed without overflow // because temp cannot be Integer.MIN_VALUE } public int lookup(int hashKey) { return hash[imod(hashKey, size)]; } |
...