Grammar
Copy Code code as follows:
For (object Objectname:prearraylist (List of Object objects)) {}
Example
Copy 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];
Public Foreach ()
{
Belle[0] = "Xi Shi";
BELLE[1] = "Wang Zhaojun";
BELLE[2] = "Diao Chan";
BELLE[3] = "Concubine Yang";
c = Arrays.aslist (Belle);
}
public void Testcollection ()
{
for (String b:c)
{
System.out.println ("Once weathered peerless:" + b);
}
}
public void Testarray ()
{
for (String B:belle)
{
System.out.println ("Once Tsing:" + b);
}
}
public static void Main (string[] args)
{
foreach each = new foreach ();
Each.testcollection ();
Each.testarray ();
}
}
For collection types and array types, we can access it through the foreach syntax. In the example above, we used to access the array in turn, which is troublesome:
Copy Code code as follows:
for (int i = 0; i < belle.length; i++)
{
String B = belle[i];
System.out.println ("Once weathered peerless:" + b);
}
Now just the following simple statement:
Copy Code code as follows:
for (String B:belle)
{
System.out.println ("Once Tsing:" + b);
}
Access to the collection is more pronounced. Before we accessed the code for the collection:
Copy Code code as follows:
for (Iterator it = C.iterator (); It.hasnext ();)
{
String name = (string) it.next ();
System.out.println ("Once weathered peerless:" + name);
}
Now we just need the following statement:
Copy Code code as follows:
for (String b:c)
{
System.out.println ("Once weathered peerless:" + b);
}
foreach is not a panacea, it also has the following disadvantages:
In the previous code, we could perform the remove operation through iterator.
Copy Code code as follows:
for (Iterator it = C.iterator (); It.hasnext ();)
{
Itremove ()
}
However, in the current foreach version, we cannot delete the objects that the collection contains. Nor can you replace the object.
At the same time, you cannot parallel a multiple set of foreach. So, when we write code, we have to look at the situation and use it.