Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if hashcode calculated exceeds the INTEGER MAX LIMIT?

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;
}
like image 549
Akh Avatar asked Dec 12 '22 01:12

Akh


1 Answers

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.

like image 62
Jon Skeet Avatar answered May 19 '23 14:05

Jon Skeet