Search code examples
javahashhashtableinteger-hashing

Java: Need help on hashing function overflow


I am working on an assignment were I have to hash 10,000 numbers into a hash table of load size .1, .2 .3 .... up to .9. My problem is that my hashing function is giving me some overflow or something of the sort. If am doing a hash for a table with load factor of .5 like 36077(mod)20,000 it gives me 16070 as the key. This only happens on numbers that are above the load factor. This is the code for my hashing function.

    public int linearHash(int in){
    int hashKey = in%hashTableArray.length;
    while(this.hashTableArray[hashKey] != 0){
        hashKey += 1;
    }
    return hashKey;
}

Thank you.


Solution

  • You are not checking that you are exceeding the index bounds of the hashTableArray in your while loop. You could do:

    while (hashKey < hashTableArray.length && this.hashTableArray[hashKey] != 0){