Item 58: Prefer for-each loops to traditional for loops

Traditional for loop distracts the programmer because of index variables. It gives you many chances to use the wrong variable. for-each loop hides the iterator or index variable.

	List<Integer> list = new ArrayList<Integer>();

	List<String> listString = new ArrayList<String>();
	// Iterate with for-each loop. Better then the traditional one!
	for (Integer integer : list) {
	// for-each loops are even greater when it comes to nested iteration
	for (Integer integer : list) {
		for (String string : listString) {
			System.out.println("nested foreach loop");

There are some cases that you do need to use an ordinary for loop. For instance, you want to replace the value of a list while you iterate a collection. Please check the book for other examples.

	// Transforming a list with ordinary for loop
	for (int i = 0 ; i < integerList.size(); i++) {
		System.out.println("before: " + integerList.get(i));
		integerList.set(i, 3);
		System.out.println("after: "+integerList.get(i));

Leave a Reply

Your email address will not be published. Required fields are marked *