简体   繁体   中英

Recursive Java method giving stack overflow error

I am a trying to figure out why I am getting stack overflow error for the following recursive method. The method is for checking an ArrayList of type Bed for availability. It needs to find numOfBeds available consecutively/together, and then return the position of the first, so I can book the specified amount consecutively starting at that position in the list. The arguments given: pos = the starting position, numOfBeds = amount to find, bedList = an ArrayList . The recursive call will have the starting point one after where an unavailable bed was found. Thanks in advance!

    public int multiEmptyBeds(int pos, int numOfBeds, ArrayList<Bed> bedList)
    {
    int check = pos;
    int count = 0;

    if(pos >= bedList.size())
        return -1;
    while(count != numOfBeds)
        {
        if(bedList.get(check).ifAvailable())
            check++;
        else
            break;
        count++;
        }
    if(count == numOfBeds)
        return pos;
    return multiEmptyBeds(check++, numOfBeds, bedList);
    }

EDIT: SOLVED! See solution/optimization below...

Your problem in recursive-call statement:

return multiEmptyBeds(check++, numOfBeds, bedList);

The semantic of suffix form of ++ operator is such, that it will change value of variable check , only after the called function returns.

You have to use prefix form increment operator ++ :

return multiEmptyBeds(++check, numOfBeds, bedList);

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