Why does java.util.Collection define next (), hasNext () directly?

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

while(collection.hasNext()){…} 

instead:

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

Of course, I know a simple way for a for loop for(E e:collection) .

Why is there an Iterator interface?

+6
java iterator collections design
source share
4 answers

This will not be thread safe . A collection could only support one “current position,” so you could not iterate over it simultaneously in two different threads.

Iterators allow several simultaneous iterative flows that do not step on each other.

+7
source share

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

This may be helpful. If Collection defines next and hasNext , this approach will be excluded.

+9
source share

I understand that the rationale for having iterators deduced from the collection is that there can be many types of them (except for just moving around the collection). You can create your own iterator to go back or do something like iterate through the DOM graph by visiting all nodes.

+3
source share

The primary reason is that the collection must have an iterative "state". You could not support multiple iterations at the same time. PHP arrays have a bit of a built-in iteration state, and that confused me.

+2
source share

All Articles