java search
Loading
Help improve Java Search

Tuesday, November 07, 2006

The Java 5 for each loop

A new article on java.net, Nuances of Java 5.0 for-each loop, discusses the Java 5 for-each loop, in great detail. The article covers common programming errors when using the for-each loop, how the enhanced for-loop compares with the equivalent implementation with the regular for-loop, how to write new classes that can be used as targets of a for-each loop compiler optimizations of the for-each loop, and a lot more. Here is a list of the talking points:
  1. The for-each loop can handle only one iteration variable.
  2. Nested iterations are allowed.
  3. Iterating over varargs. Java 5.0 now allows a variable number of arguments of a single type to be passed in as the last parameter to a method. The compiler collects these varargs parameters into an array of that type. The for-each loop can be used to iterated over the varargs.
  4. Do not modify the list during iteration
  5. When appropriate, implement java.util.RandomAccess to allow for compiler optimizations
  6. Consider returning an Iterable rather than a List
  7. Consider returning Iterable views rather than implementing Iterable
  8. Return zero length arrays or empty lists rather than nulls

1 comment:

  1. very nice of u that u have summarized all key-points of for-each loop in java so easily hat it makes easy to understand and view it as categoriesed....hank u very much....

    ReplyDelete