Xander Riga Xander Riga - 1 month ago 4
Java Question

Java Hash Table giving NullPointerException when checking if string is not null

I have a hash table that is implemented using a node array, where the node contains a string and a boolean to check if there was a string there before for when searching for an element after elements have been deleted. I am getting a nullpointerexception at a place that I don't understand how I possibly could, in this line:

while(T.getElement(place) != null)


This is my code to do the loop that is throwing the exception.

Get Element is here:

public String getElement(int index){
if (index != lastProbed)
probeCount++;
lastProbed = index;
return table[index].str;
}


And this is my node class:

class Node {

boolean hadStr;
String str;


public Node() {
str = null;
hadStr = false;
}

}


I don't understand how I could be getting a null pointer in a place where I am just checking if a string is null.

Answer

Why not

public String getElement(int index){
        if (index != lastProbed)
            probeCount++;
        lastProbed = index;
        if (table[index] != null) {
           return table[index].str;
        }
        return null;
}
Comments