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 }
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 within the loop, this does not affect the original array:
for(int x : nums) { x = x * 10; // Sem efeito no array original }
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3