The Coder's Handbook

For Each Loops

USING FOR-EACH LOOPS

Summary


A for-each loop, also known as an enhanced for loop, is a short way to loop through a collection of data. Although it can't do everything a normal for loop can do, it's handy because it makes your code much shorter and cleaner.


For-each loops can be used with both Arrays and ArrayLists.

Syntax


Consider an example where we have an ArrayList of Particle objects. We can use an enhanced for loop to iterate through each one and tell them to render themselves in our render method:


ArrayList<Particle> particles();


public void render()

{

for(Particle p : particles)

{

p.render(g);

}

}

LIMITATIONS

Using the Loop Variable


Sometimes, you might write code that needs to keep track of which count you are in when looping.


For example, maybe you're displaying text a certain distance apart and wanted to multiply by i to set the spacing.

this code needs a traditional for loop

public void render(GameContainer gc, StateBasedGame sbg, Graphics g)

{

for(int i = 0; i < quotes.size(); i++)

{

g.drawString(quotes.get(i), x, y + i * 20);

}

}

Concurrent Modification Exception


You cannot add or remove an element from an ArrayList while inside a for-each loop. If you do so, your program will throw a ConcurrentModificationException.

RESOURCES