grammar
Copy the code code as follows:
for (Object objectname : preArrayList(a list of Object objects)) {}
Example
Copy the code code as follows:
package com.kuaff.jdk5;
import java.util.*;
import java.util.Collection;
public class Foreach
{
private Collection c = null;
private String[] belle = new String[4];
publicForeach()
{
belle[0] = "Xi Shi";
belle[1] = "Wang Zhaojun";
belle[2] = "Diao Chan";
belle[3] = "Yang Guifei";
c = Arrays.asList(belle);
}
public void testCollection()
{
for (String b : c)
{
System.out.println("Once a peerless weathered person:" + b);
}
}
public void testArray()
{
for (String b : belle)
{
System.out.println("The past left a name in history:" + 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 the foreach syntax. In the above example, we used to access the arrays in sequence, which was quite troublesome:
Copy the code code as follows:
for (int i = 0; i < belle.length; i++)
{
String b = belle[i];
System.out.println("Once a peerless weathered person:" + b);
}
Now all it takes is the following simple statement:
Copy the code code as follows:
for (String b : belle)
{
System.out.println("The past left a name in history:" + b);
}
The effect of accessing collections is more obvious. Previously we accessed the collection code:
Copy the code code as follows:
for (Iterator it = c.iterator(); it.hasNext();)
{
String name = (String) it.next();
System.out.println("Once a peerless weathered person:" + name);
}
Now we only need the following statement:
Copy the code code as follows:
for (String b : c)
{
System.out.println("Once a peerless weathered person:" + b);
}
Foreach is not omnipotent, it also has the following shortcomings:
In the previous code, we could perform the remove operation through Iterator.
Copy the code code as follows:
for (Iterator it = c.iterator(); it.hasNext();)
{
itremove()
}
However, in the current version of foreach, we cannot delete the objects contained in the collection. You can't replace objects either.
Also, you cannot foreach multiple collections in parallel. Therefore, when we write code, we have to use it according to the situation.