SoFunction
Updated on 2025-03-09

Example of foreach usage in java program

grammar

Copy the codeThe code is as follows:

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

Example

Copy the codeThe code is as follows:

package .jdk5;
import .*;

import ;

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] = "Yang Guifei";
   c = (belle);
}

public void testCollection()
{
for (String b : c)
{
("Once the most weathered:" + b);
}
}

public void testArray()
{
for (String b : belle)
{
("Once upon the time of history:" + b);
}
}

public static void main(String[] args)

{
Foreach each = new Foreach();
   ();
();
}
}



For collection type and array type, we can access it through the foreach syntax. In the example above, we used to access the array in turn, which was quite troublesome:
Copy the codeThe code is as follows:

for (int i = 0; i < ; i++)
{
String b = belle[i];
("Once the weathered and peerless:" + b);
}


Now just need the following simple statement:
Copy the codeThe code is as follows:

for (String b : belle)
{
("Once upon the time of history:" + b);
 }
 


Access to collections is more obvious. Previously, we visited the code for the collection:
Copy the codeThe code is as follows:

for (Iterator it = (); ();)
{
String name = (String) ();
("Once the weathered and peerless:" + name);
}


Now we only need the following statement:
Copy the codeThe code is as follows:

for (String b : c)
{
("Once the weathered and peerless:" + b);
}


Foreach is not omnipotent either, it also has the following disadvantages:

In previous code, we can perform remove operation through Iterator.

Copy the codeThe code is as follows:

for (Iterator it = (); ();)
{
   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. So, when we write code, we have to use it according to the situation.