views:

120

answers:

4

If Collection defines hasNext() instead of iterator().hasNext(), we could write loop easier:

while(collection.hasNext()){…}

instead of:

Iterator it= collection.iterator();
While(it.hasNext()){…}

Of course, I know easy way for loop for(E e:collection) exists.

Why interface Iterator exists?

+8  A: 

Because you can have multiple valid Iterator objects for the same Collection object simultaneously.

This can be useful. If Collection defined the next and hasNext methods, this approach would be precluded.

Borealid
Multiple Iterator? Could you offer an example?
卢声远 Shengyuan Lu
Shengyuan Lu: Multiple iterators could come about by using threads as John Kugelman points out in his answer.
Rob Olmos
There are also cases where you would want more than one `Iterator` from a single thread. Any data structure where you need a lookbehind, for instance.
Borealid
+4  A: 

That would not be thread safe. The collection would only be able to maintain one "current position" so you couldn't iterate over it simultaneously in two different threads.

Having iterators allows multiple simultaneous iterating threads that don't step on each others' toes.

John Kugelman
...as long as they don't modify the collection they are pointing to. In the latter case, a ConcurrentModificationException will be thrown.
gawi
+2  A: 

Primary reason is the collection would have to have iteration "state". You couldn't support multiple iterations at the same time. PHP arrays have something like built in iteration state and it confused me.

seand
+2  A: 

I understand that the rationale for having iterators factored out of the collection is so that there can be many kinds of them (other than simply moving forward through the collection). You can create your own iterator to go backwards or do something like iterate through a DOM graph visiting all of the nodes.

Christopher Hunt