Friibo Friibo - 1 month ago 18
Java Question

Remove() method in HashTable failing tests

I've been writing a HashTable for an assignment and I've been given tests to run and pass.
As of now I'm passing all the tests apart from 3. But as far as I can tell from my own tests all the methods work fine. Apart from my Exception on the

remove()
method.

public void remove(String key) throws MapException{
int i = this.linearProbing(key);
if(hashTable[i].getKey() == key){ //line 76
numberOfEntries--;
numberOfRemovals++;
hashTable[i] = this.DEFUNCT;
}
else{
String e = "No entry of this key found";
throw new MapException(e);
}
}


When I run this test I get an error and I'm not sure what it is.

//Remove a non-existent entry. Should throw an Exception
private static boolean test4() throws MapException {
StringHashCode sHC = new StringHashCode();
float maxLF = (float) 0.5;
HashTableMap h = new HashTableMap(sHC,maxLF);
try {
h.insert("R3C1");
} catch (MapException e1) {
return false;
}
try {
h.remove("R6C8"); //line 117
return false;
} catch (MapException e) {
return true; }
}


I'll also link my MapException Class here:

import java.lang.Exception;

public class MapException extends Exception {

public MapException(){

}

public MapException(String exception){
super(exception);
}

public MapException(String exception, Throwable throwable) {
super(exception, throwable);
}

public MapException(Throwable throwable) {
super(throwable);

}

}


The error is:


Exception in thread "main" ***Test 1 failed Test 2 succeeded Test 3 succeeded java.lang.NullPointerException at HashTableMap.remove(HashTableMap.java:73) at TestHashTableMap.test4(TestHashTableMap.java:117) at TestHashTableMap.main(TestHashTableMap.java:24)

Answer
Exception in thread "main" ***Test 1 failed Test 2 succeeded Test 3 succeeded 
java.lang.NullPointerException 
    at HashTableMap.remove(HashTableMap.java:73) 
       at TestHashTableMap.test4(TestHashTableMap.java:117) 
           at TestHashTableMap.main(TestHashTableMap.java:24)

The NullPointerException means, generally, that you're trying to access an Object that doesn't really exist (or is Null).

With the line numbers you've added in the problem is clear -- the remove() checks

hashTable[i].getKey() == key

hashtable[i] returns Null, so getKey fails, throwing the null reference error.

Try:

...
public void remove(String key) throws MapException{
    int i = this.linearProbing(key);

    (hash) entry = hashTable[i];

    if((entry !=null) && (entry == key)){
        numberOfEntries--;
 ...

This will check to see if the entry exists in the table before operating on it.