Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to write an iterator?

Tags:

I know this is probably a silly question.. When would I need to write my own iterator? Is it just when designing my own container class? Are there any other times when I would want to create my own iterator?

Examples would be appropriated.

-Jon

like image 677
Jon Avatar asked Mar 24 '10 17:03

Jon


People also ask

When would you use an iterator?

Iterator in Java is an object used to cycle through arguments or elements present in a collection. It is derived from the technical term “iterating,” which means looping through. Generally, an iterator in Java is used to loop through any collection of objects.

Why iterator is used instead of for loop?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

What is the benefit of an iterator?

Benefits of Iterators. Use of an iterator simplifies the code and makes it general. Benefits of using this iterator API include: treats variables of all types, sizes, and shapes uniformly, whether they fit in memory or not, even if a single row won't fit in memory.


1 Answers

Yes, there are other times. For a few examples:

  1. A filter_iterator that only returned a filtered subset of the items in a container.
  2. A select iterator that returned only part of an object.
  3. An ostream_iterator that puts separators before or between items, instead of after them.
like image 53
Jerry Coffin Avatar answered Oct 13 '22 13:10

Jerry Coffin