HashUtils Assignment

From CSE231 Wiki
Revision as of 18:24, 2 March 2023 by Cosgroved (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

HashUtils

class: HashUtils.java Java.png
methods: toIndex
package: hash.exercise
source folder: student/src/main/java

toIndex(key,hashFunction,maxExclusive)

Note: this method should perhaps have been named toArrayIndex with the maxExclusive parameters named arrayLength.

public static <K> int toIndex(K key, ToIntFunction<K> hashFunction, int maxExclusive)

Invoking the hashFunction's applyAsInt(value) method with the provided key will return an int value between (inclusive) Integer.MIN_VALUE and Integer.MAX_VALUE, that is: between (inclusive) -2147483648 and 2147483647.

To convert this to a suitable array index, we would like to take the positive remainder of the value and the arrayLength (currently named maxExclusive).

Simply using the % operator will not due, as a negative hashCode would result in a negative array index (which would, of course, produce an array IndexOutOfBoundsException).

Using Math.floorMod(dividend,divisor) solves this problem by always returning a remainder with the sign of the divisor.