Java数组遍历:for-each循环,轻松遍历数组元素

In Java, an array is a container used to store multiple data elements of the same type. When we need to view each element in the array, we perform a “traversal” operation. There are many ways to traverse an array, and the “for-each loop” (also known as the enhanced for loop) is one of the simplest and most commonly used methods, especially suitable for beginners to quickly get started.

1. Syntax of the for-each Loop

The syntax of the for-each loop is very concise. It does not require manual management of the array index and directly accesses array elements “one by one.” The basic format is as follows:

for (dataType temporaryVariable : arrayName) {
    // Code to process each element here
}
  • dataType: Must be consistent with the type of the array elements (e.g., if the array is int[], use int here).
  • temporaryVariable: This variable temporarily stores one element of the array during each iteration (you can customize the variable name, such as num, element, etc.).
  • arrayName: The array to be traversed.

2. First for-each Loop Example

Suppose we have an array storing student scores:

int[] scores = {90, 85, 95, 78}; // The array has 4 elements

Use the for-each loop to traverse this array and print each score:

for (int score : scores) { // score is a temporary variable that takes one element in each iteration
    System.out.println(score); // Print the current element
}

When this code runs, the output will be:

90
85
95
78

In each iteration, score will “get” the next element of the array until all elements have been accessed.

3. Advantages of the for-each Loop

For beginners, the for-each loop has three significant advantages:
1. Simpler Code: No need to write array length, index initialization, or boundary checks, avoiding complex loop conditions.
2. Higher Safety: No need to worry about array out-of-bounds errors (e.g., avoiding mistakes like writing i < scores.length incorrectly).
3. More Intuitive Logic: Directly process the “element itself” without caring about the position relationship of the array, making it easy to understand.

4. Comparison with the Ordinary for Loop

If you use the traditional “indexed for loop” to traverse the array, the code will be slightly more complex:

// Traversal with a regular for loop
for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]); // Access elements via index i
}

As you can see, the ordinary for loop requires manually maintaining the index i, while the for-each loop omits these steps. If you only need to “read” the array elements (without modifying them or using the index), the for-each loop is simpler; if you need to modify elements or use the index (e.g., calculating positional relationships), the ordinary for loop is necessary.

5. Note: Can the for-each Loop Modify Array Elements?

The “temporary variable” of the for-each loop is essentially a “copy” of the array element. Modifying the temporary variable will not affect the original array. For example:

// Attempt to modify elements with a for-each loop (this will NOT work!)
for (int score : scores) {
    score = score + 5; // Wrong approach: only modifies the temporary variable, not the original array
}
System.out.println(scores[0]); // Output remains 90, no change

If you need to modify array elements, use the ordinary for loop (modify via index):

// Correct way to modify array elements (using a regular for loop)
for (int i = 0; i < scores.length; i++) {
    scores[i] = scores[i] + 5; // Modify the original array via index
}
System.out.println(scores[0]); // Output is 95

6. Summary

The for-each loop is a “powerful tool” for traversing arrays in Java. It makes the code more concise and readable, making it easy for beginners to master array traversal quickly. Remember:
- Reading array elements only (e.g., printing, statistics): Use the for-each loop first.
- Need to modify elements or use the index: Use the ordinary for loop.

Mastering the for-each loop will make array processing more efficient for you, eliminating the need for cumbersome index operations!

Xiaoye