Effective Java



Download 2,19 Mb.
Pdf ko'rish
bet237/341
Sana11.07.2022
Hajmi2,19 Mb.
#776765
1   ...   233   234   235   236   237   238   239   240   ...   341
Bog'liq
Effective Java



ITEM 58: PREFER FOR-EACH LOOPS TO TRADITIONAL FOR LOOPS
265
// Can you spot the bug?
enum Suit { CLUB, DIAMOND, HEART, SPADE }
enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT,
NINE, TEN, JACK, QUEEN, KING }
...
static Collection suits = Arrays.asList(Suit.values());
static Collection ranks = Arrays.asList(Rank.values());
List deck = new ArrayList<>();
for (Iterator i = suits.iterator(); i.hasNext(); )
for (Iterator j = ranks.iterator(); j.hasNext(); )
deck.add(new Card(i.next(), j.next()));
Don’t feel bad if you didn’t spot the bug. Many expert programmers have
made this mistake at one time or another. The problem is that the 
next
method is
called too many times on the iterator for the outer collection (
suits
). It should be
called from the outer loop so that it is called once per suit, but instead it is called
from the inner loop, so it is called once per card. After you run out of suits, the
loop throws a 
NoSuchElementException
.
If you’re really unlucky and the size of the outer collection is a multiple of the
size of the inner collection—perhaps because they’re the same collection—the
loop will terminate normally, but it won’t do what you want. For example,
consider this ill-conceived attempt to print all the possible rolls of a pair of dice:

Download 2,19 Mb.

Do'stlaringiz bilan baham:
1   ...   233   234   235   236   237   238   239   240   ...   341




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish