Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t java.util.Collection define next(), hasNext() directly?

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?

like image 401
卢声远 Shengyuan Lu Avatar asked Sep 02 '10 02:09

卢声远 Shengyuan Lu


People also ask

How does hasNext and next work in Java?

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.

What is the difference next () and hasNext () method?

hasNext() either returns true or false while next() will actually iterate to the record.

Does ArrayList have next?

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.

How does iterator hasNext work in Java?

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.


2 Answers

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.

like image 177
Borealid Avatar answered Oct 20 '22 20:10

Borealid


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.

like image 27
John Kugelman Avatar answered Oct 20 '22 21:10

John Kugelman