Unit 6: Lesson 8: Removing Elements

I was going through exercises 2-4 and kept getting a OutOfMemoryError. Class debugged the problem and found the following solution.

System.out.println("Original list: " + numList + "\nSize: " + numList.size());

//adding this fixed the lesson, but is never mentioned, am I missing something?
**int nNumList = numList.size();**

for (int index = 0; index < nNumList; index++) {
 int randomNum = (int)(Math.random() * 50) + 10;
  numList.add(100);
}

Seems this is creating an infinite loop. Doesn’t seem like the directions are clear or maybe this is an error. Thoughts?

Hi @Mr.Rhodes, I am seeing the same thing that you are seeing. The for loop is running for as long as the statement index < numList.size(); is true. Since we are adding new elements inside the for loop the size of the ArrayList continues to grow. So yes, you are correct that the loop is infinite and the program crashes when it is out of memory. I don’t see this being made clear in the instructions either. I will make this aware to the curriculum team at support@code.org and if you don’t mind sending them an email as well I think that will help prioritize modifying the instructions (or code) for this level.

As far as your fix, you set a fixed number for the condition to check against. Namely, the original size of the list.

Thanks again for bringing this to the forum! I know it helps teachers and definitely improves the curriculum in the long run.

Best,
-Sam

2 Likes