J2SE of new characteristics---the enhancement of circular statements

Source: Internet
Author: User
Tags execution new features
J2se| Loop | statement
A statement like this before:



void Cancelall (Collection c) {



for (Iterator i = C.iterator (); I.hasnext ();) {



TimerTask TT = (timertask) i.next ();



Tt.cancel ();



}



}



You can write this later:



void Cancelall (Collection c) {



for (Object o:c)



((TimerTask) O). Cancel ();



}



Sometimes we might write this code:



List suits = ...;



List ranks = ...;



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.next ()));



This code does not work as we think, because every time the execution of the second for statement throws the execution of I.next (), we actually do not have the purpose of traversing the I and may cause a nosuchelementexception exception.



One way to solve this problem is to rewrite 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 ()));



}

With the new features of the Java language, we can write this:



for (Suit suit:suits)



for (Rank rank:ranks)



Sorteddeck.add (new card (suit, rank));



Is this code beautiful?




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.