Time to open the Champagne -- Java 1.5 is out, and the language has finally come of age! With the new Java 1.5 specification, Java now contains features that make it feel like a proper "grown-up" language. The rest of this article will introduce you to these new features. To try out the features for yourself, simply download Java 1.5 from Sun’s website and give it a whirl. Note that you’ll need to compile the code using the –source 1.5 option; otherwise, you’ll get compilation errors when using the new features.
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:
private void printCards
(Collection deck) { Iterator iter = deck.iterator(); while (iter.hasNext()) { Card card = (Card) iter.next(); System.out.println(card.toString()); } }
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:
List
<Card> deck = new ArrayList<Card>();
for (CardSuit suit : CardSuit.values()) { for (CardValue val : CardValue.values()) { Card card = new Card(val, suit); deck.add(card); } }