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.add(1);
list.add(2);
list.add(3);
List<String> listString = new ArrayList<String>();
listString.add("string1");
listString.add("string2");
listString.add("string3");
// Iterate with for-each loop. Better then the traditional one!
for (Integer integer : list) {
System.out.println(integer);
}
// 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));
}