ArrayList Traversals
| English | Chinese | Pinyin |
|---|---|---|
| ConcurrentModificationException | 并发修改异常 | bìng fā xiū gǎi yì cháng |
Looping over a list
- Traverse an ArrayList just like an array, but with its methods.
- Indexed:
for (int i = 0; i < list.size(); i++) { ... list.get(i) ... } - For-each:
for (String s : list) { ... s ... }— clean for reading values. size()(notlength) bounds the indexed loop.
The same patterns
- Sum, count, min/max, and search all work the same as with arrays.
- Just swap
a[i]forlist.get(i)anda.lengthforlist.size(). - The accumulator and max/count logic is identical.
- Everything you learned for array traversal carries over.
Reading vs. modifying
- Use the for-each loop to just read each element.
- Use an indexed loop with
set(i, x)to change an element in place. - For structural changes (adding/removing), use the indexed loop carefully.
- Reading is simple; removing while looping needs extra care (next lesson).
Don't modify during for-each
- Adding or removing during a for-each loop throws a ConcurrentModificationException 并发修改异常.
- The for-each loop assumes the list doesn't change structure underneath it.
- To remove while traversing, use an indexed loop (and manage the index).
- Reading with for-each is always safe; structural edits are not.
Bound an indexed ArrayList loop with list.size(), not .length, and never structurally modify during a for-each. Calling add/remove inside a for (x : list) throws a ConcurrentModificationException. To delete while traversing, use an indexed loop — and remember remove(i) shifts later elements, so don't blindly i++ past the shifted element.
Summing an ArrayList
- Indexed:
for (int i = 0; i < list.size(); i++) { sum += list.get(i); } - For-each:
for (int x : list) { sum += x; }(autoboxing/unboxing handles Integer↔int). - Both total the list; for-each is cleaner for read-only.
Traverse an ArrayList with an indexed loop (i < list.size(), list.get(i)) or a for-each loop (read-only). The array patterns (sum, count, min/max, search) all carry over. Never add/remove during a for-each — it throws a ConcurrentModificationException; use an indexed loop for structural edits.
Summing an ArrayList by index
Bound with size(), read with get(i) (list = [10,20,30]).
The correct condition for an indexed ArrayList loop is...
ArrayList uses size(); arrays use length.
Adding or removing during a for-each loop over a list throws...
for-each assumes the structure doesn't change underneath it.
The array traversal patterns (sum, count, max) work the same for an ArrayList.
Just swap a[i]/a.length for list.get(i)/list.size().
To safely remove elements while traversing a list, you should use...
for-each can't structurally modify; the indexed loop can (carefully).
A for-each loop over a list is safe for reading each value.
Reading is fine; only structural edits during for-each are unsafe.