← Back to Study Guide← 返回学习指南

Removing from an ArrayList while looping forward正向循环中删除 ArrayList 元素

Run one Java statement or condition check at a time. Watch nums and i change.每次执行一条 Java 语句或检查一次条件,观察 nums 和 i 的变化。

Code代码

  1. // nums holds 4, 6, 5, 8
  2. int i = 0;
  3. while (i < nums.size()) {
  4. if (nums.get(i) % 2 == 0) {
  5. nums.remove(i);
  6. }
  7. i++;
  8. }

State状态

Variable变量Value值
nums[4, 6, 5, 8]
i—
Condition条件—

Use ← and → to step. The final condition is false, so the loop stops.使用 ← 和 → 逐步运行。最后条件为假,循环结束。