Difference between revisions of "HashUtils Assignment"
Line 1: | Line 1: | ||
− | |||
==HashUtils== | ==HashUtils== | ||
{{CodeToImplement|HashUtils|toIndex|hash.exercise}} | {{CodeToImplement|HashUtils|toIndex|hash.exercise}} | ||
Line 16: | Line 15: | ||
Using [https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int- Math.floorMod(dividend,divisor)] solves this problem by always returning a remainder with the sign of the divisor. | Using [https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int- Math.floorMod(dividend,divisor)] solves this problem by always returning a remainder with the sign of the divisor. | ||
− |
Latest revision as of 18:24, 2 March 2023
HashUtils
class: | HashUtils.java | |
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.