Enhanced for loop

Until now, we’ve use out classic counter-based loop to traverse through arrays and lists.

But when you don’t really need the index and just want to use a construct where it says,

“For every item (current) in the collection, use current for something”

This kind of traversal is provided by the enhanced for loop.

Syntax

1
2
3
for(type current: array/list) {
	use current
}

Example with array

1
2
3
4
5
6
int[] data = {10, 70, 20, 90};

int total = 0;
for(int item: data) {
	total = total + item;
}

Example with list

1
2
3
4
5
6
7
8
9
10
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(70);
list.add(20);
list.add(90);

int total = 0;
for(int item: list) {
	total = total + item;
}

When should I use the enhanced for loop?

Enhanced for loops are used when you don’t need the index for anything besides accessing the item at that index.

Examples of when enhanced for loop should be used

Examples when it’s better (IMO) to use a counter-based loop