Example foreach usage in a Java program

  • 2020-04-01 03:16:07
  • OfStack

grammar


for (Object objectname : preArrayList( a Object List of objects )) {}

The sample


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] = " Diau charn ";
belle[3] = " Yang ";
   c = Arrays.asList(belle);
}
public void testCollection()
{
for (String b : c)
{
 System.out.println(" Once upon a time :" + b);
}
}
public void testArray()
{
for (String b : belle)
{
  System.out.println(" Once in the history of the name :" + b);
}
}
public static void main(String[] args)
{
Foreach each = new Foreach();
   each.testCollection();
each.testArray();
}
}


For both the collection type and the array type, we can access it through the foreach syntax. In the above example, we used to access arrays in sequence, which was quite troublesome:

for (int i = 0; i < belle.length; i++)
{
String b = belle[i];
System.out.println(" Once upon a time :" + b);
}


Now we just need the following simple statement:

for (String b : belle)
{
   System.out.println(" Once in the history of the name :" + b);
 }
 


The access to the collection is more obvious. Before we access the collection of code:

for (Iterator it = c.iterator(); it.hasNext();)
{
String name = (String) it.next();
System.out.println(" Once upon a time :" + name);
}


Now we just need the following statement:

for (String b : c)
{
System.out.println(" Once upon a time :" + b);
}


Foreach isn't a panacea either, and it has the following drawbacks:

In the previous code, we could 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.
Also, you can't parallel multiple sets of foreach. So when we write code, it depends.


Related articles: