Java & J2EE Page 4 - Java Comes of Age |
It is common to iterate through Collections, yet the Java idiom for doing so has, until now, been a little cumbersome. We would have to declare an Iterator, explicitly check whether another object is available (as a loop condition), and then retrieve the object if there is one available. And there's that tricky cast to contend with too. Java 1.5 has simplified the idiom, so that, for example, instead of writing:
you can now write:
This saves a bit of typing but, more importantly, is less error-prone. I certainly welcome the omission of the cast. You can also use the enhanced for-loop for iterating through arrays. I omitted to mention in the earlier section on enumerations that the method values() can be applied to an enumeration to retrieve an array of all the possible values. So using the new for-loop construct you can create a deck of cards with:
blog comments powered by Disqus |