Question

(Sorry for any format errors, I'm a very novice programmer and this is my first question). I have a moviearray array with a physical size of 100 and a logical size of 15 (the program is a mock movie store that allows for movies to be added and removed by 'adding' or 'buying'. However, in the following line of code, I have a heap space error:

    for (int i=0;i<moviearray.length;i++)
    {
        while(moviearray[i].getTitle() !=null)
        {
            CollTitle.append(moviearray[i].getTitle()+"\n");
        }
    }

I am really confused because my array is only 100 at maximum. Thank you in advance.

Was it helpful?

Solution

You are increasing i in for but inside is a infinite while loop. In result you are creating infinite number of Strings objects.

OTHER TIPS

there is no need for a while loop. The value of moviearray[i].getTitle() never changes, so it will remain true if it was not null to begin with, which means the while loop will loop forever. Just do a if(moviearray[i].getTitle() != null) instead.

The loop you have never evaluate to false.

while(moviearray[i].getTitle() !=null)
{
    CollTitle.append(moviearray[i].getTitle()+"\n");
}

is like having as you never change the i or the title.

    while(true)
    {
        CollTitle.append(moviearray[i].getTitle()+"\n");
    }

This cause the the out of memory as you in each iteration put something on the heap.

to solve our problem replace while with if

if(moviearray[i].getTitle() !=null)
{
    CollTitle.append(moviearray[i].getTitle()+"\n");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top