Home >Java >javaTutorial >A brief analysis of java's foreach loop
When using the foreach loop to traverse arrays and collections, there is no need to obtain the length of the array and collection, and there is no need to access array elements and collection elements according to the index. The foreach loop automatically traverses each element of the array and collection.
foreach的语句格式: for(type variableName : array|connection){ //variable自动迭代访问每一个元素 }
Example:
public class ForEachTest { public static void main(String[] args) { String[] books = {"java","c","c++","c#","asp"}; for(String book : books) { System.out.println(book); } } }
Output:
java
c
c++
c
#asp
public class ForEachTest { public static void main(String[] args) { String[] books = {"java","c","c++","c#","asp"}; for(String book : books) { book = "hello world!"; System.out.println(book); } System.out.println(books[0]); } }
Output:
hello world!
hello world!
hello world!
hello world!
hello world!
java
So foreach loops are generally only suitable for array traversal, data extraction and display, etc., and are not suitable for complex operations such as adding, deleting, and using subscripts.
The foreach statement is an enhanced version of the for statement under special circumstances, which simplifies programming and improves the readability and safety of the code (you don’t have to worry about the array going out of bounds). It is a good supplement to the old for statement.
It is recommended that foreach should not be used where foreach can be used. When using a collection or array index, foreach seems to be unable to do its job. At this time, it is time to use the for statement. foreach is generally used in conjunction with generics
For more articles related to a brief analysis of java's foreach loop, please pay attention to the PHP Chinese website!