Java Tip #6: Use the for-each of Java5 whenever possible

The Java Tips series gets another entry, yay! I'll keep within the plain Java language this time, no frameworks or other fancy tricks, just basic Java know-how.


Advice

Use Java5's for-each loop instead of manually iterating over arrays or collections whenever it is possible.

Code-Example

Before

...
// access using index
for (int i = 0; i < offerList.getMembers().size(); i++) {
    CustomizedOfferOverviewDTO dto = (CustomizedOfferOverviewDTO)offerList.getMembers().get(i);
...
}
...
// access using iterator
Iterator iter = m_elements.iterator();
while (iter.hasNext()) {
    ILoadable loadable = (ILoadable)iter.next();
...
}
...

After

...
for(CustomizedOfferOverviewDTO dto : offerList.getMembers()) {
...
}
...
for(ILoadable loadable : m_elements) {
...
}
...

Benefit

Readability gain. The for-each makes it a lot easier to iterate over collections and arrays and to read and recognize the code. Furthermore the Java compiler might also be able to optimize the loop a bit better internally but in general this improvement is beyond measuring accuracy and therefore is not an argument in this case.

Remarks

This only works as long as it's not modifying the collection or array beneath it. If deleting or replacing elements, you have to use the previous-style looping again where you have direct access to the Iterator.

|

Similar entries