Why are iterators useful?
QUESTION
Why are iterators useful?
Select one
a) Iterators give you direct access to private variables
b) Iterators are easier to loop over than a while loop
c) Improve information hiding by not revealing how a collection class is implemented
d) Iterators prevent infinite loops
e) Iterators walk down a collection faster than a for loop
ANSWER
Iterators useful for Iterators prevent infinite loops so the correct option is (d).
EXPLANATION
a) The option-a is wrong: The private variables cannot be accessed outside the class even with an iterator.
b) The option-b is wrong: While loop stops the iteration when the condition is false and the iterator stops iterating when the end of the list is reached. Even though these to loops have their own usage ways, we cannot say that iterators are easier to loop.
c) The option-c is wrong: Iterators won’t improve information hiding by not revealing how a collection class is implemented.
d) The option-d is true.
Generally, if a condition never becomes false, a for loop or a while loop may result in an infinite loop. An iterator can never run into an infinite loop since it iterates until the end of some collection.
e) Option-e is wrong too: Iterators walk down a collection but might not be faster than for loop.
Also Read: Design a TestScores class that has member variables to hold three test scores.