ArrayList Loop Boundary Error
Consider the following code segment. When executed, this code produces an IndexOutOfBoundsException. Which statement best explains the cause of this error?
import java.util.ArrayList;
public class DebugExample {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(2);
nums.add(3);
for (int i = 0; i <= nums.size(); i++) {
System.out.print(nums.get(i) + " ");
}
}
}
A
The print statement should use println instead of print.
B
The ArrayList declaration is missing a generic type on the left-hand side.
C
The add() method is incorrectly used; it should include an index as a parameter.
D
The loop condition uses ‘<=’ instead of ‘<’, which attempts to access an element at index nums.size() and causes an out-of-bound error.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE