0

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;
asked Dec 14, 2014 at 3:10
1
  • Where is table declared? It's likely that table is null. Commented Dec 14, 2014 at 3:14

3 Answers 3

2

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.

answered Dec 14, 2014 at 3:16
2

The NullPointer Exception could be because either:

  1. table is null, or
  2. table[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.

answered Dec 14, 2014 at 3:15
1

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())

answered Dec 14, 2014 at 3:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.