Prefer For-Each Loops to For Loops

Summary

Use for each loops in preference to indexed for loops.

Details

The for each loop introduced with Java 5 avoids the potential out-by-one errors of indexed for loops and is more concise than code using iterators.

Bad

  1. public List<String> selectValues(List<Integer> someIntegers) {
  2. List<String> filteredStrings = new ArrayList<String>();
  3. for (int i = 0; i != someIntegers.size(); i++) {
  4. Integer value = someIntegers.get(i);
  5. if (value > 20) {
  6. filteredStrings.add(value.toString());
  7. }
  8. }
  9. return filteredStrings;
  10. }

A little better

  1. public List<String> selectValues(List<Integer> someIntegers) {
  2. List<String> filteredStrings = new ArrayList<String>();
  3. for (Integer value : someIntegers) {
  4. if (value > 20) {
  5. filteredStrings.add(value.toString());
  6. }
  7. }
  8. return filteredStrings;
  9. }