Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

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

Compliant Solution

One compliant implementation is to call This compliant solution calls a function that returns a true (a modulus that is always positive) modulus.

Code Block
bgColorCCCCFF
/* remainder function giving 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)];
}

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
bgColorCCCCFF
public int lookup(int hashKey) {
  if (hashKey < 0)
    return hash[(-hashKey) % size];
  return hash[hashKey % size];
}

...