Why Should I Use Java's For-Each Syntax?
For-Each
Back in Java 5, Oracle introduced the For-Each syntax for looping over classes implementing the Iterable interface.
It looks like this:
final Collection<String> collection = fantasyMethod(); for (final String string : collection) { System.out.println(string); }
instead of this:
final Collection<String> collection = fantasyMethod(); for (final Iterator<String> iterator = collection.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); }
Big improvement!
Why Use It?
Make your code more readable and decrease the likelihood of errors. More code to accomplish something is a bad thing - less is more.
When Else Can I Use It?
It isn't just for iterators! You can use it for arrays:
final String[] stringArray = new String[2]; stringArray[0] = "foo"; stringArray[1] = "bar"; for (final String string : stringArray) { System.out.println(string); }
When Can't I Use It?
When you need access to the index. For example:
final String[] stringArray = new String[2]; stringArray[0] = "foo"; stringArray[1] = "bar"; for (int i = 0; i < stringArray.length; i++) { System.out.println(string + i); }
What Next?
I'll show another way to iterate over items in a Collection or other Iterable classes in Java.
??
Originally published on my blog: