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代码
- // nums holds 4, 6, 5, 8
- int i = 0;
- while (i < nums.size()) {
- if (nums.get(i) % 2 == 0) {
- nums.remove(i);
- }
- i++;
- }
State状态
| Variable变量 | Value值 |
|---|---|
| nums | [4, 6, 5, 8] |
| i | — |
| Condition条件 | — |
Use ← and → to step. The final condition is false, so the loop stops.使用 ← 和 → 逐步运行。最后条件为假,循环结束。