Java for and foreach Loops
- The variable in the for loop condition is evaluated only once! Take a look at the final picture
- The foreach statement is newly added to Java 5. When traversing arrays and sets, foreach has good performance.
- Foreach is a simplified for statement, but foreach cannot replace for loop. It can be said that any foreach can be rewritten as a for loop, but the opposite won't work.
- Foreach is not a keyword in java. The loop object of foreach is generally a set, such as List, ArrayList, sorted List, Vector, and array.
- Foreach format:
For (element type T name of each loop element O: loop object ){
// Perform O operations
}
I. Common usage methods.
Foreach traverses the List.
Ii. Limitations.
Although foreach can traverse arrays or sets, it can only be used for traversing and cannot modify arrays or sets during traversal, the for loop can modify the source array or set during traversal.
Set
Special attention !!