Java Enhanced for Loop Detailed explanation
Enhancedfor
Loops (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 implementedIterable
Collection of interfaces (e.g.List
、Set
wait).
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 tradition
for
Loop, there is no need to get the array length or call the iterator of the collection.
Widely applicable:
- Can be used in arrays,
List
、Set
、Map
(TravelingentrySet()
、keySet()
orvalues()
)。
3.2 Limitations
Unable to modify the collection structure:
- Enhanced
for
In a loop, the set cannot be directly performedadd
orremove
Operation, 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:
Enhancedfor
The index of an element cannot be directly obtained in the loop. If you need indexing, you need to use traditionalfor
cycle:
String[] fruits = {"Apple", "Banana", "Cherry"}; for (int i = 0; i < ; i++) { ("Index " + i + ": " + fruits[i]); }
Only sequential access is supported:
Applicable toIterable
Collection of interfaces (e.g.List
、Set
), not suitable for scenarios that require random access.
4. traverse the enhanced for Map
4.1 Traversal keySet
TraversalMap
All 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, enhanced
for
It is the best choice.
Traversal collection:
- Traversal
List
、Set
etc collections, especially when the collection does not need to be modified.
TraversalMap
:
- use
entrySet()
When enhancedfor
Concise 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?
Enhancedfor
Used 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 enhancedfor
Manually maintain the index:
String[] fruits = {"Apple", "Banana", "Cherry"}; int index = 0; for (String fruit : fruits) { ("Index " + index + ": " + fruit); index++; }
7. Underlying implementation
Enhancedfor
The essence of the loop is to use itIteratorTo achieve it.
pseudocode
forIterable
Object:
for (Type element : collection) { Iterator<Type> it = (); while (()) { Type element = (); // Circulation body } }
For arrays:
for (Type element : array) { for (int i = 0; i < ; 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.
Enhancedfor
Looping 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!