Brief analysis of Java foreach loop

  • 2020-04-01 02:34:19
  • OfStack

When using foreach loop to iterate over groups and collections, there is no need to obtain the length of the array and collection, and there is no need to access the array and collection elements according to the index. The foreach loop automatically iterates over each element of the group and collection.


foreach Statement format:  
for(type variableName : array|connection){ 
     //Variable automatically iterates over each element
} 

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

Therefore, foreach loop is generally only suitable for array traversal, data extraction and display, etc., and is not suitable for complex operations such as adding and deleting subscripts.

The foreach statement is an enhanced version of the for statement in special cases to simplify programming, improve code readability and security (without fear of array overbounds). This is a nice addition to the old for statement.

Where foreach is encouraged, don't use for. Foreach doesn't work well when it comes to indexing collections or arrays, so it's time to use the for statement. Foreach is generally used in conjunction with generics    


Related articles: