1

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...

2
  • can you give us an input that throws a stack overflow error? Commented Oct 26, 2013 at 21:25
  • I just created an ArrayList called bedList and added 25 Bed objects to it. Then I changed the 'booked' variable value to true for the first 5 beds(position 0-4 in list). Now I give the following argument to thsi method(0, 4, bedList). Writing a JUnit test, with the expected return value of 5, as from that element onwards all are available ofcourse so it should pass the test, but unfortunately it fails due to stack overflow Commented Oct 26, 2013 at 21:26

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Holy smokes! I thought about that change after I shut down my PC yesterday, then totally forgot about it. I realize now why it would give a stack overflow error, due to it never moving past the unavailable bed. Thanks alot man!
BTW, you're wasting CPU, it is absolutly not necessary to write the new value back to check. I'd just use check + 1
@Ingo Yes, you're right, int this case check + 1 would be better.
@Ingo Good suggestion. Will make that change! Thanks! I am still not in the optimization stage, but these kinda little things can help if implemented as you go...

Your Answer

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.