Unit 2 Cycle 2 Day 11: Error: Loop Modifying Collection
Share
Error: Loop Modifying Collection
Section 2.13 — Informal Code Analysis
Key Concept
A common error pattern involves modifying a collection or string while iterating over it. While the AP CSA exam does not use iterators, the concept appears when a loop processes a string and the processing changes the string's length. For example, removing characters from a string inside a for loop that uses the original length causes the loop to access indices beyond the shortened string. The safe approach is to build a new string rather than modifying the original, or to iterate backward when removing elements.
A method is intended to count even numbers in a string of digits.
The call countEven("1234") causes an error. What is the fix?
Answer: (A) Change i <= to i <
When i = digits.length() (which is 4), substring(4, 5) throws StringIndexOutOfBoundsException because the string only has indices 0-3. Changing <= to < prevents i from reaching the length.
Why Not the Others?
(B) Starting at i=1 would skip the first digit, which is not the intended behavior.
(C) This would count odd numbers instead of even numbers, changing the logic.
(D) charAt(i) returns a char, which cannot be directly used with Integer.parseInt.
Common Mistake
i <= length allows i to equal the length, which causes an out-of-bounds error on the substring call. Always use i < length for string traversal.
AP Exam Tip
The standard string traversal bounds are i = 0; i < s.length(). Using <= is almost always a bug.