Friday, September 24, 2010

Foreach Syntax

Java SE5 introduces a new and more succinct for syntax, for use with arrays and containers. This is often called the foreach syntax, and it means that you don’t have to create an int to count through a sequence of items—the foreach produces each item for you, automatically.

foreach will also work with any object that is Iterable

The foreach syntax not only saves time when typing in code. More importantly, it is far easier to read and says what you are trying to do (get each element of the array) rather than giving the details of how you are doing it ("I’m creating this index so I can use it to select each of the array elements.").
Example:

control/ForEachFloat.java

No comments:

Post a Comment