Effective Java



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



CHAPTER 9
GENERAL PROGRAMMING
264
Item 58: Prefer for-each loops to traditional 
for
 loops
As discussed in Item 45, some tasks are best accomplished with streams, others
with iteration. Here is a traditional 
for
loop to iterate over a collection:
// Not the best way to iterate over a collection!
for (Iterator i = c.iterator(); i.hasNext(); ) {
Element e = i.next();
... // Do something with e
}
and here is a traditional 
for
loop to iterate over an array:
// Not the best way to iterate over an array!
for (int i = 0; i < a.length; i++) {
... // Do something with a[i]
}
These idioms are better than 
while
loops (Item 57), but they aren’t perfect. The
iterator and the index variables are both just clutter—all you need are the elements.
Furthermore, they represent opportunities for error. The iterator occurs three times
in each loop and the index variable four, which gives you many chances to use the
wrong variable. If you do, there is no guarantee that the compiler will catch the
problem. Finally, the two loops are quite different, drawing unnecessary attention
to the type of the container and adding a (minor) hassle to changing that type.
The for-each loop (officially known as the “enhanced 
for
statement”) solves
all of these problems. It gets rid of the clutter and the opportunity for error by hid-
ing the iterator or index variable. The resulting idiom applies equally to collec-
tions and arrays, easing the process of switching the implementation type of a
container from one to the other:

Download 2,19 Mb.

Do'stlaringiz bilan baham:
1   ...   232   233   234   235   236   237   238   239   ...   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