Do we still need an iterator design pattern?

Hi guys I am studying design patterns and I found an Iterator. Do we still need to use it? Since we have a collection, I am confused why we still need an iterator design template.

thank

+5
source share
9 answers

Collections are actually heavily using iterators in both languages. Whenever you look at the elements of a collection, there is some kind of iterator, even if you do not see it explicitly in the code. I gave examples in Java, as I am more familiar with it.

Preferred idiom for iterating over a build prior to Java 5 - explicitly using Iterator:

for (Iterator i = c.iterator(); i.hasNext(); ) {
  doSomething((Element) i.next()); // (No generics before 1.5)
}

And since Java 5:

for (Element e : elements) {
  doSomething(e);
}

-, , Iterator .

+7

IEnumerator<T> - , IEnumerable<T> . IEnumerable<T>.

Linq-To-Objects, # 3. #.

# 3 , yield return.

foreach .

+6

IEnumerable - :)

+2

Java , , Iterator.remove() .

+2

, !

1) O(n^2) .

for (int i = 0; i < list.size(); i++)
  list.get(i).foo();

№5, head 4 . № 6 , , ( ). , , O(n). !

2) size(). . , . , (for(i=0;i<size;i++)), .

, . , .

3) ? , . , , - .

, , .

+2

, , , .

, IDataReader , IEnumerable iterator , .

+1

, . , , . .

  • , . ( , , , )
  • (, , DB, ).
  • , , i.
  • . , . , .

linq , . , for foreach.

+1

Java # . .

(, , Java), .

0

- , .

/ -

  • .

,    , String    + .   , .

  • -

,   , , . ,   , .    .

  • , .

  • , ,

, , , .

This is actually what makes template algorithms possible, because now they need to focus only on what they do with the content or collections, and ignore the type of collections passed to them.

I would go so far as to say that an iterator template is the simplest and most basic element from which the whole concept of template collections, such as STL, begins.

0
source

All Articles