CHAPTER 9
GENERAL PROGRAMMING
266
If instead you use a nested for-each loop, the problem simply disappears. The
resulting code is as succinct as you could wish for:
// Preferred idiom for nested iteration on collections and arrays
for (Suit suit : suits)
for (Rank rank : ranks)
deck.add(new Card(suit, rank));
Unfortunately, there are three common situations where you
can’t
use for-each:
•
Destructive filtering
—If you need to traverse a collection removing selected
elements, then you need to use an explicit iterator so that you can call its
remove
method. You can often avoid explicit traversal by using
Collection
’s
removeIf
method, added in Java 8.
•
Transforming
—If you need to traverse a list or array and replace some or all
of the values of its elements, then you need the list iterator or array index in
order to replace the value of an element.
•
Do'stlaringiz bilan baham: