SoFunction
Updated on 2025-04-17

Detailed explanation of Java enhanced for loop syntax

Java Enhanced for Loop Detailed explanation

EnhancedforLoops (also known as "for-each" loops) are Java fromJDK 5A convenient loop syntax that was introduced in the beginning was designed to simplify iterative operations on array or collection classes.

1. Basic syntax

Syntax format

for (type variable : Iterative objects) {
    // Circulation body}
  • type: The type of element in iterated object.
  • variable: Stores the variables of the current element at each iteration.
  • Iterative objects: Array or implementedIterableCollection of interfaces (e.g.ListSetwait).

2. Use examples

2.1 Iterate over the array

public class EnhancedForArray {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        for (int num : numbers) {
            (num); // Output: 1, 2, 3, 4, 5        }
    }
}

2.2 Traversing the collection

import ;
import ;
public class EnhancedForList {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        ("Apple");
        ("Banana");
        ("Cherry");
        for (String fruit : fruits) {
            (fruit); // Output: Apple, Banana, Cherry        }
    }
}

3. Features and limitations

3.1 Features

Simplicity

  • There is no need to manually manage indexes or iterators, and the code is easier to read.
  • Comparison of traditionforLoop, there is no need to get the array length or call the iterator of the collection.

Widely applicable

  • Can be used in arrays,ListSetMap(TravelingentrySet()keySet()orvalues())。

3.2 Limitations

Unable to modify the collection structure

  • EnhancedforIn a loop, the set cannot be directly performedaddorremoveOperation, otherwise it will be thrownConcurrentModificationException
  • Example:
List<String> list = new ArrayList<>();
("A");
("B");
for (String s : list) {
    if (("A")) {
        (s); // An exception will be thrown    }
}

If you need to modify the collection structure, you can useIterator

Iterator<String> iterator = ();
while (()) {
    String s = ();
    if (("A")) {
        (); // Safely delete elements    }
}

Unable to access the index

EnhancedforThe index of an element cannot be directly obtained in the loop. If you need indexing, you need to use traditionalforcycle:

String[] fruits = {"Apple", "Banana", "Cherry"};
for (int i = 0; i < ; i++) {
    ("Index " + i + ": " + fruits[i]);
}

Only sequential access is supported

Applicable toIterableCollection of interfaces (e.g.ListSet), not suitable for scenarios that require random access.

4. traverse the enhanced for Map

4.1 Traversal keySet

TraversalMapAll keys:

import ;
import ;
public class EnhancedForMap {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        ("A", 1);
        ("B", 2);
        ("C", 3);
        for (String key : ()) {
            ("Key: " + key + ", Value: " + (key));
        }
    }
}

4.2 Traversal entrySet

More efficiently traverse keys and values ​​simultaneously:

for (<String, Integer> entry : ()) {
    ("Key: " + () + ", Value: " + ());
}

5. Applicable scenarios

Iterate through the array

  • For arrays with known size and no modification, enhancedforIt is the best choice.

Traversal collection

  • TraversalListSetetc collections, especially when the collection does not need to be modified.

TraversalMap

  • useentrySet()When enhancedforConcise and efficient.

Simplify the code

  • Avoid manually managing indexes or iterators.

6. Frequently Asked Questions

6.1 Why can't an enhanced for loop modify a collection?

EnhancedforUsed under the bottom layerIteratorTo traverse the collection, if you directly modify the collection structure (such as adding or removing elements), it will cause the iterator to fail and throw itConcurrentModificationException

6.2 How to access indexes in enhanced for?

Can be enhancedforManually maintain the index:

String[] fruits = {"Apple", "Banana", "Cherry"};
int index = 0;
for (String fruit : fruits) {
    ("Index " + index + ": " + fruit);
    index++;
}

7. Underlying implementation

EnhancedforThe essence of the loop is to use itIteratorTo achieve it.

pseudocode

forIterableObject:

for (Type element : collection) {
    Iterator&lt;Type&gt; it = ();
    while (()) {
        Type element = ();
        // Circulation body    }
}

For arrays:

for (Type element : array) {
    for (int i = 0; i &lt; ; i++) {
        Type element = array[i];
        // Circulation body    }
}

8. Summary

advantage

  • Simplified code: Suitable for most iterative scenarios, avoiding manual processing of indexes and iterators.
  • High readability: concise syntax, focusing on element processing.

shortcoming

  • The index cannot be operated directly.
  • Modifying the collection structure is not supported.
  • Suitable for sequential access, not for random access scenarios.

EnhancedforLooping is a further abstraction of the iterator pattern in Java. It makes traversal simpler and more efficient, and is a very commonly used tool in development.

This is the end of this article about the detailed explanation of Java enhanced for loops. For more related Java enhanced for loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!