Syntax
for (Object objectname : preArrayList(一个Object对象的列表)) {}
Example
package com.kuaff.jdk5; import java.util.*; import java.util.Collection; public class Foreach { private Collection c = null; private String[] belle = new String[4]; public Foreach() { belle[0] = "西施"; belle[1] = "王昭君"; belle[2] = "貂禅"; belle[3] = "杨贵妃"; c = Arrays.asList(belle); } public void testCollection() { for (String b : c) { System.out.println("曾经的风化绝代:" + b); } } public void testArray() { for (String b : belle) { System.out.println("曾经的青史留名:" + b); } } public static void main(String[] args) { Foreach each = new Foreach(); each.testCollection(); each.testArray(); } }
For both collection types and array types, we can access it through foreach syntax. In the above example, we had to access the array sequentially before, which was quite troublesome:
for (int i = 0; i < belle.length; i++) { String b = belle[i]; System.out.println("曾经的风化绝代:" + b); }
Now we only need the following simple statement:
for (String b : belle) { System.out.println("曾经的青史留名:" + b); }
The effect of accessing the collection is more obvious. In the past, our code for accessing the collection:
for (Iterator it = c.iterator(); it.hasNext();) { String name = (String) it.next(); System.out.println("曾经的风化绝代:" + name); }
Now we only need the following statement:
for (String b : c) { System.out.println("曾经的风化绝代:" + b); }
Foreach is not omnipotent, it also has the following shortcomings:
In the previous In the code, we can perform the remove operation through Iterator.
for (Iterator it = c.iterator(); it.hasNext();) { itremove() }
However, in the current foreach version, we cannot delete the objects contained in the collection. You can't replace objects either.
At the same time, you cannot foreach multiple collections in parallel. Therefore, when we write code, we have to use it according to the situation.
For more articles related to foreach usage examples in java programs, please pay attention to the PHP Chinese website!