Java--Enhanced for loop

Source: Internet
Author: User

Enhanced for Loop

The enhanced for loop is an advanced for loop that comes out of JDK1.5 and is designed to iterate through arrays and collections. Its internal principle is actually a iterator iterator , so in the process of traversal, the elements in the collection can not be removed or deleted operations.

Format:

For (the data type variable of the element: Collection collection or array) {

}

It is used to traverse collection and arrays. Typically, only the elements are traversed, and the collection elements are not removed or deleted during traversal.

Exercise one: Traverse array int[] arr = new int[]{11,22,33};

for (int n:arr) {//variable n represents the array element to be traversed

SYSTEM.OUT.PRINTLN (n);

}

Exercise two: Iterating through the collection

collection<string> coll = new arraylist<string> ();

Coll.add ("A1");

Coll.add ("A2");

Coll.add ("A3");

Coll.add ("A4");

For (String str:coll) {//variable str represents the collection element that is traversed

System. out. println (str);

}

What is the difference between an enhanced for loop and an old for loop?

Note: The new for loop must have a target that is traversed. The target can only be a collection or an array.

Recommendation: When iterating through an array, if only for traversal, you can use the enhanced for if you want to manipulate the elements of arrays, you can use the old for loop to manipulate them through the corner label.

Java--Enhanced for loop

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.