What happens if hashcode calculated exceeds the INTEGER MAX LIMIT?

hash, hashmap, hashtable, integer, java

Solution

I assume hashCodes will be positive integers.

No, not necessarily. They're just integers. They can definitely be negative, and it's fine to have integer overflow while computing a hash code. An ideal hash code will be spread uniformly across the whole of its range (`int` in this case). Anything using a hash code definitely needs to take into account the possibility of the value being negative.

Problem

Here is the hashCode() implementation from Java HashTable Class. What if the number of elements in the hashtable is huge and the hashcode exceeds the INTEGER MAX LIMIT -2,147,483,648 to 2,147,483,647 ? I assume hashCodes will be positive integers. ``` public synchronized int hashCode() { int h = 0; if (count == 0 || loadFactor < 0) return h; // Returns zero loadFactor = -loadFactor; // Mark hashCode computation in progress Entry[] tab = table; for (int i = 0; i < tab.length; i++) for (Entry e = tab[i]; e != null; e = e.next) h += e.key.hashCode() ^ e.value.hashCode(); loadFactor = -loadFactor; // Mark hashCode computation complete return h; } ```

Original source