Analysis of the _java of the Java foreach Loop

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.