Java Null Pointer Exceptions in while Loops
Below is some code to delete a number from an array in a hash-table. It uses a quadratic function. How do I avoid a null pointer exception in the while statement? Thanks!
public Integer[] quadDelete(Integer[] arr开发者_Go百科ay, int k)
{
int i =0;
while(array[i]!=k && i<array.length){ //This causes a null pointer exception
i = ( hashFunction(k) + 4*i + 7*i*i) % divideAmount;
if(array[i]==k)
array[i]= null;
}
return array;
}
Check whether array[i]
is null first before the array[i]!=k
. Also check whether array
itself is null or not before entering the while
loop.
Assuming that array
isn't null
:
- You aren't incrementing
i
, so ifarray[i]==k
, thenarray[i]
is being set tonull
. You're getting the a NPE the second time through the loop when it tries to unbox the value from an Integer. - You should check that
i
is in range before trying to accessarray[i]
, not afterwards, in the while-loop test.
If you say you are getting the NPE in the loop condition the only possible reason could be that the array object passed is null. Check if array is null before you check the loop condition.
Here's a version of the code corrected to avoid exceptions:
public Integer[] quadDelete(Integer[] array, int k) {
int i = 0;
while (i < array.length && array[i] != null && array[i] != k) {
i = (hashFunction(k) + 4 * i + 7 * i * i) % divideAmount;
if (i < array.length && array[i] != null && array[i] == k) {
array[i] = null;
}
}
return array;
}
But I don't think that this version of the code makes much sense anyway:
When the
if
condition is true, you assignnull
toarray[i]
which makes thewhile
condition false ... so the loop terminates.If we assume that
hashFunction
is a pure function of its argumentk
, then in some cases the recalculation ofi
will give the same value, and the loop won't terminate.
精彩评论