简体   繁体   中英

StackOverFlow error recursion

A task has been set to use a recursive method inside a custom hashtable to find the next available place inside the array to store a key and a value.

Starting at the startPos(which is the hashed value of the key), and incrementing the stepNo each time to keep track of the place, if it is occupied I have a method to find the next location depending on the probe type/number of steps taken so far. For some reason I am getting an over flow error.

private int findEmpty(int startPos, String key, int stepNum) {
        if(arr[startPos] == null)
            return startPos;

        int next = getNextLocation(startPos, stepNum++, key);
        findEmpty( next ,key, stepNum);

        return startPos;
    }

The below method takes finds the next location to check based on its probe type, it takes the startPos(hashed value of the key) the stepNo(to keep track of the steps after hashing to place) and the key its self.

private int getNextLocation(int startPos, int stepNum, String key) {
        int step = startPos;
        switch (probeType) {
        case LINEAR_PROBE:
            step++;
            break; 
        case DOUBLE_HASH:
            step += doubleHash(key);
            break;
        case QUADRATIC_PROBE:
            step += stepNum * stepNum;
            break;
        default:
            break;
        }
        return step % max;
    }

Thanks any advice or criticism is welcome.

If arr[startPos] != null for your entire array (ie your array is full), the recursion would never end.

In addition, you do nothing with the value returned by the recursive all - findEmpty( next ,key, stepNum) . I'm assuming you want to return it instead of always returning startPos .

You probably want to make this change :

private int findEmpty(int startPos, String key, int stepNum) 
{
    if(arr[startPos] == null)
        return startPos;

    int next = getNextLocation(startPos, stepNum++, key);
    return findEmpty( next ,key, stepNum);
}

In addition, you must have a way to detect when the array is full, in which case you should either re-size it or throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM