That Special For Loop#
Using arrays with loops is in fact so common that there is a specialized type of loop just for this very case! It looks very similar to our known for
loop, but has a slightly different set of set of commands in its parentheses:
String[] movies = {
"Iron Man 3",
"Thor: The Dark World",
"Captain America: The Winter Soldier",
"Guardians of the Galaxy",
"Avengers: Age of Ultron",
"Ant-Man"
};
for (String movie : movies) {
println(movie); // what is this magic?!
}
That is extremely short. Let's still take the time to unpack it:
for
tells us, that a loop is about to begin.- in the
()
parentheses, it looks like we're declaring a new variablemovie
(yes! we are!) and then there's a:
colon and after that there's the name of the arraymovies
. - after that we get a block of code, which uses the variable
movie
.
Notably, we don't have a counter variable here. There's no int i ...
like we did so many times before. You also do not need to check the array's .length
property. All of that is taken care of for you. By our new friend, the for-each-loop. That is also how you would read that code in your head "for each movie in movies".
When to use the for-each
loop#
Whenever you just need to go over all items in your list, the for-each loop is a great choice. It's concise and is not easily broken. I would suggest using this loop whenever you work with arrays and don't have any reason to use another type of loop.
When not to use the for-each
loop#
Sometimes, you can use the iterator (usually i
) to accomplish multiple things at once. Maybe it does not only work as your array index, because you also need to draw something to the screen like this:
String[] movies = {
"Captain America: Civil War",
"Doctor Strange",
"Guardians of the Galaxy Vol. 2",
"Spider-Man: Homecoming",
"Thor: Ragnarok",
"Black Panther",
"Avengers: Infinity War",
"Ant-Man and the Wasp",
"Captain Marvel",
"Avengers: Endgame",
"Spider-Man: Far From Home "
};
size(800, 300);
background(0);
textSize(20);
for (int i = 0; i < movies.length; i++) {
fill(30 * i, 255, 255);
text(movies[i], 10, 30 + i * 25);
}
In this example, i
does a whole lot of work. It changes the color, it selects which movie title we want and it changes the text's y
coordinate so we don't print all the different texts in the same place on the screen.