Two Hidden Bugs Lurk in Java's Simple HashMap Bucket Index Formula
A seemingly straightforward line of Java code used to map hash keys to array buckets contains two distinct bugs that developers commonly overlook. Java's % operator is a remainder operator, not a true modulo, meaning negative hashCode() values can produce negative array indices and trigger an ArrayIndexOutOfBoundsException. The intuitive fix of wrapping the result in Math.abs() fails silently for Integer.MIN_VALUE, which has no positive 32-bit counterpart and returns itself unchanged. Java 8's Math.floorMod() solves both edge cases by always returning a non-negative result when the divisor is positive, while java.util.HashMap avoids division entirely by using a bitmask with power-of-two capacities for speed. Additionally, relying on low bits alone can cause excessive collisions when a class's hashCode() varies mostly in high bits, which is why HashMap first mixes bits using h ^ (h >>> 16) before indexing.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in