I was tyring to test if my array is empty, but I always get a null pointer exception for some reason. I don't understand since my test actually test if the value is null. Here is the code where it gets stucks. I get the null pointer on the While loop:
private int findIndex(String key) {
int index = calculateHashCode(key);
while (table[index] != null && !table[index].getKey().equals(key)) {
index = (index + 1) % TABLE_SIZE;
}
return index;
}
EDIT
table is declared like this:
static HashEntry[] table;
3 Answers 3
If table
is null
. The act of performing table[index]
dereferences the array, which causes a NullPointerException
. A null array is not a empty array. A null array roughly corresponds to that fact that there is no array at all, and the table
variable points to nothing.
Please make the distinction between a null array, an empty array and a null element in a non-empty array.
Array is null:
table == null
Array is empty:
table.length == 0
Element 0 in array is null:
table[0] == null
Similarly, you cannot call methods from a null
object. If table[index]
returns a null element, calling getKey() upon it could result in NullPointerException
. Same goes if getKey() is null and then trying to call equals() on that.
Please note an uninitialized array is implicitly null
. Make sure you actually initialize the array.
The NullPointer Exception could be because either:
table
is null, ortable[index].getKey()
returns null
In case 1, the evaluation of the expression table[index] != null
is a read of an item from the table array. This will throw a NullPointerException if table is null.
In case 2, if table[index].getKey()
returns null, then the expression table[index].getKey().equals(key)
is calling a method (equals) on a null object reference which results in the exception.
Your table
isn't initialised, declare as
static HashEntry[] table = new HashEntry[TABLE_SIZE];
so that it isn't null.
Also, if HashEntry.getKey()
can return null
, make sure you check for this (or just flip the equals, i.e. !key.equals(table[index].getKey())
table
declared? It's likely thattable
is null.