+ 2

Purpose of iterators

Why are iterators used if you can access a collection's value with an "extended for" cycle?

31st Dec 2016, 9:06 PM
BaHaMuT - avatar
1 Antwort
+ 4
An iterator is useful if used in a while loop (your loop will continue until the collector will have no more elements), otherwise the "extended for" cycle sometimes will be not correct. e.g. I wrote a code to calculate prime numbers: those numbers would be calcolated only when necessary, calling the hasNext() method. So, if you use an iterator cycle you would have no limits, in other situation to do a for cycle you should first determine the number of elements in the list and this would stop the loop immediately! I hope you would understand sorry for my english..
1st Jan 2017, 12:22 AM
Michael Isac Girardi
Michael Isac Girardi - avatar