Java 5 for loop syntax example

Java 5 FAQ: Can you share some examples of the Java 5 for loop syntax?

Sure. As a bit of background, in the days before Java 5 you could create a for loop to iterate over a collection of strings like this:

// assumes there is a method named "getList()"
List list = getList();

for (Iterator it = list.iterator(); it.hasNext();) {
  String value=(String)it.next();
}

Java 5 for loop syntax

That’s not too bad, but with the release of Java 5 your for loops can now be a little tighter, like this:

List list = getList();

for (String s : list)  {
  // treat s as a String here; no casting needed
}

I like this syntax a lot because it gets me out of the business of constantly having to cast the items in a list (or collection). 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.