Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fixed color coding

...

In this noncompliant code example, the integer hashKey references an element of the hash array. However, as the hash key is not guaranteed to be positive, the lookup function may fail, triggering a java.lang.ArrayIndexOutOfBoundsException on all negative inputs.

Code Block
bgColorFFCCCC#FFcccc
private int SIZE = 16;	
public int[] hash = new int[SIZE];
	
public int lookup(int hashKey) {
  return hash[hashKey % SIZE];
}

...

This compliant solution calls a method that returns a modulus that is always positive.

Code Block
bgColorCCCCFF#ccccff
// 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 < 0) ? ((-i) % j) : (i % j);
}
	
public int lookup(int hashKey) {
  return hash[imod(hashKey, size)];
}

...

Alternatively, an explicit range check must be performed on the numerator at every susceptible point as demonstrated in this compliant solution.

Code Block
bgColorCCCCFF#ccccff
public int lookup(int hashKey) {
  if (hashKey < 0)
    return hash[(-hashKey) % size];
  return hash[hashKey % size];
}

...