杰瑞科技汇

Java iterator for循环怎么用?

Of course! The for loop in Java has a special syntax designed specifically for iterating over collections and arrays that implement the Iterable interface. This is often called an enhanced for-loop or a for-each loop.

Java iterator for循环怎么用?-图1
(图片来源网络,侵删)

It provides a clean, readable, and less error-prone way to loop through elements.


The Basic Syntax

The syntax is straightforward:

for (Type variableName : iterableObject) {
    // Code to execute for each element
}

Let's break that down:

  • for: The keyword that starts the loop.
  • Type variableName: You declare a new variable. The Type must match the type of elements stored in the collection.
    • variableName will hold the current element in each iteration.
  • : This is the key part of the syntax, read as "in".
  • iterableObject: This is the collection (like a List, Set) or array you want to loop over. It must be an object of a class that implements the java.lang.Iterable interface (which includes all the major collection classes) or be an array.

How it Works Under the Hood

When you use an enhanced for-loop with a collection (like a List), the Java compiler automatically converts it into a traditional loop using an Iterator.

Java iterator for循环怎么用?-图2
(图片来源网络,侵删)

Your Code:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println(name);
}

What the compiler essentially does (simplified):

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Get an iterator from the list
Iterator<String> iterator = names.iterator();
// Loop as long as there is a next element
while (iterator.hasNext()) {
    // Get the next element and assign it to the variable
    String name = iterator.next();
    System.out.println(name);
}

This is why the object you're looping over must be Iterable—it must have an iterator() method that returns an Iterator.


Examples

Example 1: Iterating a List (Most Common)

This is the classic use case.

Java iterator for循环怎么用?-图3
(图片来源网络,侵删)
import java.util.Arrays;
import java.util.List;
public class ForEachLoopExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry", "Date");
        System.out.println("My favorite fruits:");
        // Loop through the list of fruits
        for (String fruit : fruits) {
            System.out.println("- " + fruit);
        }
    }
}

Output:

My favorite fruits:
- Apple
- Banana
- Cherry
- Date

Example 2: Iterating an Array

The enhanced for-loop works just as well with arrays.

public class ArrayIterationExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        System.out.println("Array elements:");
        // Loop through the array of numbers
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output:

Array elements:
10
20
30
40
50

Example 3: Iterating a Set

Sets don't have a defined order, so the loop will reflect that.

import java.util.HashSet;
import java.util.Set;
public class SetIterationExample {
    public static void main(String[] args) {
        Set<String> uniqueWords = new HashSet<>();
        uniqueWords.add("Hello");
        uniqueWords.add("World");
        uniqueWords.add("Java");
        System.out.println("Unique words in the set:");
        for (String word : uniqueWords) {
            System.out.println(word);
        }
    }
}

Output (order may vary):

Unique words in the set:
Java
World
Hello

When to Use (and When NOT to Use) the Enhanced For-Loop

DO use it when:

  • You need to read every element in a collection or array from start to finish.
  • You do not need to know the index of the current element.
  • You are not modifying the collection itself (e.g., removing elements).

AVOID it when:

  • You need to remove elements from the collection while iterating. This will cause a ConcurrentModificationException. You must use an explicit Iterator and its remove() method.

    // WRONG - Will throw ConcurrentModificationException
    List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
    for (String name : names) {
        if (name.equals("Bob")) {
            names.remove(name); // Problem!
        }
    }
    // CORRECT - Using an explicit Iterator
    List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
    Iterator<String> iterator = names.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        if (name.equals("Bob")) {
            iterator.remove(); // Correct way to remove
        }
    }
    System.out.println(names); // Output: [Alice, Charlie]
  • You need the index of the element. If you need to know the position (e.g., to get the next or previous element), use a traditional for loop.

    List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
    // Enhanced for-loop gives you the element, not the index
    for (String name : names) {
        // System.out.println(name + " is at index ???"); // You don't know the index
    }
    // Traditional for-loop gives you the index
    for (int i = 0; i < names.size(); i++) {
        String name = names.get(i);
        System.out.println(name + " is at index " + i);
    }
  • You need to modify the elements in the collection. The loop variable is a copy of the element, so changing it won't affect the original collection.

    List<String> names = new ArrayList<>(Arrays.asList("alice", "bob", "charlie"));
    // This does NOT change the original list!
    for (String name : names) {
        name = name.toUpperCase(); // 'name' is a temporary copy
    }
    System.out.println(names); // Output: [alice, bob, charlie]
    // To modify elements, use a traditional for loop or a stream
    for (int i = 0; i < names.size(); i++) {
        names.set(i, names.get(i).toUpperCase());
    }
    System.out.println(names); // Output: [ALICE, BOB, CHARLIE]

Summary

Feature Enhanced For-Loop (for-each) Traditional For-Loop (for (int i...)) Iterator Loop (while (it.hasNext()))
Readability Excellent. Very concise and clear. Good. Explicit about the index. Good. Explicit about the iteration process.
Index Access No. Yes. i is the index. No.
Element Modification No. Modifies a copy. Yes. list.set(i, ...) works. No. Modifies a copy.
Safe Removal No. Throws ConcurrentModificationException. No. Throws IndexOutOfBoundsException. Yes. Use iterator.remove().
Use Case Simple traversal, reading all elements. When index is needed, modifying elements. Safe removal during iteration.
分享:
扫描分享到社交APP
上一篇
下一篇