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?
Basic Usage. The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
hasNext() either returns true or false while next() will actually iterate to the record.
The hasNext() method returns true if there are more elements in the ArrayList and otherwise returns false. The next() method returns the next element in the ArrayList.
boolean hasNext(): It returns true if Iterator has more element to iterate. Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws 'NoSuchElementException' if there is no next element.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With