Difference between revisions of "HashUtils Assignment"

From CSE231 Wiki
Jump to navigation Jump to search
 
(One intermediate revision by the same user not shown)
(No difference)

Latest revision as of 18:24, 2 March 2023

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.