J2SE5.0 instance --- Enhancement of cyclic statements

xiaoxiao2021-03-06  15

Enhancement of cyclic statements

Previously a statement like this:

Void Cancelall (Collection C) {for (Iterator i = C.ITerator (); I.hasNext ();) {TIMERTASK TT = (TIMERTASK) I.Next (); tt.cancel ();}} can be written later :

Void Cancelall (Collection C) {for (Object O: C) ((Timertsk) o) .cancel ();} Sometimes we may write this code:

List suits = ...; list sorteddeck = new arraylist (); for (iTerator i = suits.iterator (); i.hasnext ();) for (Iterator J = ranks.ITerator () J.HASNext ();) sorteddeck.add (new card (i.next (), j.ness ())); this code will not work as we envisaged because of the second for statement Execution will initiate an execution of I.Next (), in fact we do not reach the purpose of traversing I, and may cause a Nosuchelementexception exception. One way to solve is to rewrite into the following code:

For (iTerator i = suits.iterator (); I.hasNext ();) {suit suit = (suit) i.next (); for (Iterator j = ranks.ITerator (); j.hasnext ();) sorteddeck .add (new card (suit, j.next ())))))));} Using the new features of the Java language, we can write:

For (Suit Suit: Suits) for (Rank Rank: Ranks) sorteddeck.add (New Card (Suit, Rank)); Is this code very beautiful?

转载请注明原文地址:https://www.9cbs.com/read-46243.html

New Post(0)