Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor changes

...

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
bgColor#ccccff
// 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)];
}

...