IndexOutOfBoundsException for Virtual Ecosystem

Hello.

I am having trouble with a program, where there is a likelihood of it crashing due to an IndexOutOfBoundsException error from an arrayList. It is an ecosystem program that creates “animal objects” and adds them to an arrayList. The likelihood of the problem becomes larger when the environment becomes crowded, that is, when many animals exist at the same time.

I figure that the problem, which occurs in lines with .get(i) functions, (e.g., Animal a = animals.get(i); ) is due to that function trying to get the last item on a list that has not yet increased by one to match the appropriate length (it is always of the sort: Index x, Size: x, x being the same number). I am guessing that it occurs because of both disruptive events trying to occur at almost exactly the same time.

I was hoping that if any of you have met the same, or a similar problem, and have found a way around it, might share that so that I may implement an appropriate solution. I have looked through the forums for similar topics and haven’t found a solution. For example, I am already going backwards through the arrayList.

I do not want to post code just yet, in the hope that the description in and of itself might be enough for someone to recognize the problem and provide a solution. The program is large and unwieldy, and making a simplified version might take some time, which would be wasted if the description of the problem is good enough by itself. If absolutely necessary, however, I will attempt at creating the simplified code that illustrates the issue, but I am hoping it does not need to come to that just yet.

Thank you.

Add a test which first checks if I is less than the size of the array

I know it sounds simple but I have experienced this often, and even spent hours trying to debug as in my mind there was no reason why it should be out of bounds

1 Like

This should only happen if you are using multiple threads to update and read the arraylist. If your application is single threaded then there is a logical error in your code.

1 Like

Thank you @paulgoux. I did that and I am glad to say it worked.

1 Like