I am researching the java iterator interface and cannot understand why it is created this way.
Why hasNext Java iterator use hasNext and next instead of combining them into one method?
this is a typical use of the java iterator
Iterator iter = //iterator from a list while(iter.hasNext()){ Object obj = iter.next(); // do something to obj }
why not
Iterator iter = //iterator from a list Object obj = null; try { while(true){ obj = iter.next(); // do something to obj } } catch (NoSuchElementException e) {}
Clearly this approach looks ugly, but what happens if next returns null when the reach ends, throwing an exception instead? how code can be simplified to
Iterator iter = //iterator from a list Object obj = null; while((obj = iter.next()) != null){ // do something to obj }
this is how NSEnumerator works in Objective-C
NSEnumerator *enumerator = // from an array while (id obj = [enumerator nextObject]) { // do something to obj }
This increases the overhead of implementing a custom iterator .
It also makes the Java iterator not thread safe. For example, ArrayList has one element. Two threads simultaneously request the same iterator for this hasNext list. Then both threads will see true , and they will call next on this iterator. Because there is only one element, and the iterator is set twice, which will definitely lead to an exception or error.
I know there is a thread-safe iterator, but I'm not sure if it is being implemented, but I think there are many locks that make it inefficient.
I think the problem is that validation and updating do not happen due to atomicity, and I don’t understand why Java developed the iterator interface.
Update
I see that null can be a value, so my approach is not valid. But is there any possible workaround for the problems that I mentioned above?