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:
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.