Question

I'm trying to do a method that automatically creates a new hashTable with 1.25 more capacity, but I have a overflow error. The code is:

public void reHash (){

    Config.MAX_ESTACIONS = (int) (Config.MAX_ESTACIONS * 1.25);
    Vector<EstacioHash>[] newHashTable = new Vector[Config.MAX_ESTACIONS];

    EstacioHash nouElement = new EstacioHash();

    for (int i=0; i<hashTable.length;i++){
        for (int k=0; k<hashTable[i].size();k++){

            nouElement.key = hashTable[i].get(k).key;
            nouElement.value = hashTable[i].get(k).value;

            int position = hashFunction(nouElement.key);
            newHashTable[position].add(nouElement); <---- OverFlow here
        }
    }

    hashTable = newHashTable;

}

Why I have an overFlow? The programs run correctly without the rehash function. The hash function is:

public int hashFunction (Object clau){

    String clauMinuscules = ((String) clau).toLowerCase(); 

    char[] key = clauMinuscules.toCharArray(); 
    int result=0;

    for (int i=0;i<key.length;i++){
        result = (result + key[i]^i)%Config.MAX_ESTACIONS;
    }

    return result;
}
Was it helpful?

Solution

I don't think you have an overflow but more a NullPointerException.

The default value for an Object is null. When creating the new table, you have an array full of null values.

You need to initialize each entry of the newHashTable before trying to get the Vector at some position and add something into it.

Vector<EstacioHash>[] newHashTable = new Vector[Config.MAX_ESTACIONS];
for (int i=0; i<newHashTable.length;i++){
    newHashTable[i] = new Vector<EstacioHash>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top