Posted By

cpjobling on 03/01/07


Tagged

list iterator foreach


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

zdroshnya


Iteration through a Generic List (Java 5 version)


 / Published in: Java
 

This code uses the new Java 5 foreach loop to iterate through every element of a list. It avoids the need to declare an iterator.

  1. List<String> listOfStrings = new LinkedList<String>( );
  2.  
  3. listOfStrings.add("Why");
  4. listOfStrings.add("Iterate");
  5. listOfStrings.add("When");
  6. listOfStrings.add("You");
  7. listOfStrings.add("Can");
  8. listOfStrings.add("Avoid");
  9. listOfStrings.add("It!");
  10.  
  11. for (String s: listOfStrings) {
  12. System.out.println(s);
  13. }

Report this snippet  

You need to login to post a comment.