...
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)]; } |
Wiki Markup |
---|
Note that {{Integer.MIN_VALUE |
- Integer.MIN_VALUE == 1 + Integer.MAX_VALUE
.)}} must be handled specially in the {{imod()}} method. The \[[JLS 2005|AA. Bibliography#JLS 05]\] 15.15.4 (Unary Minus Operator) says: |
For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.
Compliant Solution
Alternatively, an explicit range check must be performed on the numerator at every susceptible point as demonstrated in this compliant solution.
...
Wiki Markup |
---|
\[[JLS 2005|AA. Bibliography#JLS 05]\] [§15.15.4 Unary Minus Operator|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.15.4] and [§15.17.3 Remainder Operators|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3] |
...