Akh
Akh

Reputation: 6043

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;
}

Upvotes: 4

Views: 4778

Answers (2)

george_h
george_h

Reputation: 1592

Sometimes getting an overflow on the integer may be unsuitable to your needs. I say this as sometimes. I still have yet to encounter this situation but I would like to prevent it.

I'll paste you the code I use to generate a hashcode. I usually do it by taking all vars from an object and convert them to strings and do my calculations.

public static int generateHashCode(String ... args)
{
    int length = 0;
    char[] cArray = null;
    if(args.length == 1) {
        length = args[0].length();
        cArray = args[0].toCharArray();
    }
    else {
        for(int i = 0; i < args.length; i++) {
            length += args[i].length();
        }

        cArray = new char[length];
        int incrementer = 0;
        for(int i = 0; i < args.length; i++) {
            String str = args[i];
            for(int j = 0; j < str.length(); j++) {
                cArray[incrementer] = str.charAt(j);
                ++incrementer;
            }
        }
    }

    int h = 0;
    for (int i = 0; i < cArray.length; i++) {
        h = 31*h + cArray[i];
    }

    return h;
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500873

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.

Upvotes: 13

Related Questions