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