Purpose: The for-each loop is used to sequentially traverse the elements of an array or collection, from beginning to end.
Syntax:
for(tipo var-iter : conjunto) { // bloco de instruções }e
Operation: At each iteration, the next element of the array is assigned to the iteration variable, which must have a type compatible with the elements of the array.
Advantages:
Limitations:
The iteration variable is read-only, meaning it cannot be used to change the underlying array.
The loop loops through all elements of the array unless a break statement is used to exit the loop early.
Example of Limitation:
Even changing the iteration variable inside the loop, this does not affect the original array:
for(int x : nums) { x = x * 10; // Sem efeito no array original }e
Use with Arrays and Collections: The for-each loop can also be used to cycle through elements of other collections in Java, in addition to arrays, such as those provided by the Collections Framework.
The above is the detailed content of The for-each style for loop. For more information, please follow other related articles on the PHP Chinese website!