Topic 4.7 — Enhanced for Loop for ArrayLists

Goal: use the enhanced for loop (for-each) to traverse an ArrayList, know when it’s the best choice, and understand limitations (especially with updating/removing).

The big idea

The enhanced for loop is a clean way to read every element in an ArrayList when you don’t need the index.

It’s great for “sum/count/max” patterns, but it’s not the right tool when you need to modify the list structure.

Syntax

for (Type item : list) {
  // use item (the element value)
}

Just like arrays: you get each element value, one by one.

Example: print all elements

for (String s : words) {
  System.out.println(s);
}

Great use: sum / count / max

int sum = 0;
for (int x : nums) {
  sum += x;
}

int countNeg = 0;
for (int x : nums) {
  if (x < 0) countNeg++;
}

int max = nums.get(0);
for (int x : nums) {
  if (x > max) max = x;
}

Limitation: updating elements is tricky

Changing the loop variable does not replace the element in the list.

for (int x : nums) {
  x = x + 1; // ❌ does not change nums
}

If you need to set values, use an indexed loop with set(i, ...).

Limitation: removing during for-each

Removing elements while using an enhanced for loop can cause errors (and is not the intended usage pattern).

// Avoid this pattern
for (Integer x : nums) {
  if (x == 0) {
    nums.remove(x); // ❌ may cause problems
  }
}

Use an indexed loop when you must modify

// Replace 0 with 99
for (int i = 0; i < nums.size(); i++) {
  if (nums.get(i) == 0) {
    nums.set(i, 99);
  }
}

// Remove all 0s safely (backward loop)
for (int i = nums.size() - 1; i >= 0; i--) {
  if (nums.get(i) == 0) {
    nums.remove(i);
  }
}

Quick self-check

  1. When is an enhanced for loop the best choice for an ArrayList?
  2. Why doesn’t changing the loop variable update the list?
  3. What should you use if you need to replace values at specific indexes?
  4. What’s a safe loop direction when removing elements by index?
  5. Write a for-each loop that counts how many strings have length > 5.

← Back to Unit 4 topics