When you iterate through arrays and collections using a Foreach loop, you do not need to get the length of the array and the collection to access the array elements and the collection elements based on the index, and the Foreach loop automatically iterates through the array and each element of the collection.
Copy Code code as follows:
foreach's statement format:
for (type variablename:array|connection) {
Variable automatic iterative access to each element
}
Example:
Copy Code code as follows:
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
Copy Code code as follows:
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 this cycle is generally only suitable for the traversal of arrays, extraction of data display, etc., is not suitable for increasing the deletion and use of the subscript and other complex operations.
The foreach statement is an enhanced version of the For statement in particular, simplifying programming and improving the readability and security of the code (not to be afraid of array bounds). Relatively old for statement is a good supplement.
Advocate a place where you can use foreach and stop using for. In the case of a collection or an array index, foreach seems powerless, and this is the time to use a for statement. foreach general combined with generic use of