Loading...

Java Iterating

Create an ArrayList<String> named tags, add oak then pine, and walk the list with for (String t : tags) printing each word. Compile Lane.java and run java Lane. The screen should show two lines: oak, then pine. Each pass of the loop prints one value. Walking every value in the collection is what this page teaches.

Walk every value once

On the HashSet page you checked size and contains without a loop. On the for-each page earlier in the course you walked a fixed array. This page walks an ArrayList the same for-each way, then shows an indexed walk with get. The collection grows with add first. The loop comes after the values are stored.
Open Lane.java. Keep the public class name Lane so the file name matches. Delete leftover HashSet, contains, Bin, Desk, and map put/get demos. Also delete any Scanner or nextLine. The program must not wait for typing.
Near the top, above public class Lane, write:
import java.util.ArrayList;
Inside main, create the list and add two words:
ArrayList<String> tags = new ArrayList<String>();
tags.add("oak");
tags.add("pine");
Then write the for-each header and body:
for (String t : tags) { System.out.println(t); }
The colon sits between the element type-and-name and the collection. Each pass sets t to the next word. Do not write a counter in this first demo. Save before you compile.

Lane for-each ArrayList

java
import java.util.ArrayList;

public class Lane {
    public static void main(String[] args) {
        ArrayList<String> tags = new ArrayList<String>();
        tags.add("oak");
        tags.add("pine");
        for (String t : tags) {
            System.out.println(t);
        }
    }
}

From the folder that holds Lane.java, run javac Lane.java. When parentheses, braces, angle brackets, colons, and semicolons match, javac writes no line of its own. Then run java Lane — not java Lane.java, and not java ArrayList. Leave the .java ending off the run command.
The program should print two lines and stop: oak, then pine. It should not ask you to type. If the terminal waits for keyboard input, a nextLine call from an older exercise is still in a file. Delete that call and keep the create, the two add lines, and the for-each.
Walk the run once. Java starts at Lane.main. The list holds oak then pine. The first pass sets t to oak and prints oak. The second pass sets t to pine and prints pine. Then the loop ends. Nothing else should print. If you see only 2, you printed size() instead of walking the values. If you see a single line [oak, pine], you printed the whole list object instead of each element — keep the for-each body as println(t). If you see true or leaf, a Bin or Desk demo is still running — switch to java Lane.
If javac says it cannot find ArrayList, the import is missing or after the class line. Move import java.util.ArrayList; above public class Lane. If you write for (String t : tags) with no braces and more than one body line later, keep this page’s body as one println inside braces so the shape stays clear. Spelling the collection name after the colon must match the list you created: tags, not a leftover slots name from the array for-each page.

Indexed walk with get

A second demo walks the same list with a counted for and get. You see the slot number path beside the for-each path.

Lane indexed get walk

java
import java.util.ArrayList;

public class Lane {
    public static void main(String[] args) {
        ArrayList<String> tags = new ArrayList<String>();
        tags.add("oak");
        tags.add("pine");
        for (int i = 0; i < tags.size(); i++) {
            System.out.println(tags.get(i));
        }
    }
}

Compile and run the same way. The screen again shows oak, then pine. The header uses i from 0 while i < tags.size(). Each body call tags.get(i) reads one slot. This is the list-methods get habit inside a loop. Prefer the for-each file as the first teaching path when you do not need the index number on the screen. Keep the indexed file to prove both walks print the same two lines for this list. If you start i at 1 by mistake, the first printed word would be pine and oak would be skipped — keep i at 0 for the full walk.
Do not rely on HashSet print order for a quiz screen on this page. Sets do not promise oak before pine. The ArrayList demos keep a stable order for the two lines you expect. Stay with ArrayList for the teaching files so the quiz screen stays predictable.

Size alone is not a walk

A third file shows the leftover habit of printing only the count. That is useful on the HashSet page, but it is not iterating.

Lane size only not a walk

java
import java.util.ArrayList;

public class Lane {
    public static void main(String[] args) {
        ArrayList<String> tags = new ArrayList<String>();
        tags.add("oak");
        tags.add("pine");
        System.out.println(tags.size());
    }
}

That file prints 2 — one number, not the words. Use it only as a contrast. The iterating lesson’s kept files print each value with for-each or with indexed get. Do not submit the size-only file as the quiz path for the two-line screen.

Compared with for-each on arrays and with HashSet checks

Earlier, for-each walked int[] or String[] slots. Here the colon still works, but the right-hand name is an ArrayList. On the HashSet page, size and contains answered without printing every value. This page prints every value. A leftover Bin contains demo is a different lesson. For this page keep Lane with the for-each that prints oak then pine.
When old Bin.java files still sit nearby, leave them alone or delete them only if they confuse which class you run. Run java Lane after you compile the walk file from this lesson.

What this leaves for wrappers

This page walks collection values. The next page covers wrapper types such as Integer beside primitive int when collections need objects. Stay with for-each and indexed get on ArrayList here. Do not invent wrapper demos as a requirement on this page.

Before wrappers

You can import java.util.ArrayList, add oak and pine, and print each word with for (String t : tags). You can also walk with for (int i = 0; i < tags.size(); i++) and tags.get(i). Compile Lane.java and run java Lane. The screen shows oak then pine. The next page is wrappers, where object types stand beside primitives for collection storage.
Keep the import. Keep the two adds before the loop. Keep for-each as the first teaching walk. Those habits are the checkpoint before you move on. When both lines print after the for-each, iterating did its job for this lesson and you are ready for the next topic.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top