开发者

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:

  1. You aren't incrementing i, so if array[i]==k, then array[i] is being set to null. You're getting the a NPE the second time through the loop when it tries to unbox the value from an Integer.
  2. You should check that i is in range before trying to access array[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 assign null to array[i] which makes the while condition false ... so the loop terminates.

  • If we assume that hashFunction is a pure function of its argument k, then in some cases the recalculation of i will give the same value, and the loop won't terminate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜