I am doing a research on java iterator
interface and cannot understand why it is designed like that.
Why java iterator use hasNext
and next
instead merge them into one method?
this a typical usage of 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) {}
It is clear this approach looks ugly but what happen if next
return null for when reach to end instead throw an exception? than code can be simplify to
Iterator iter = //iterator from a list
Object obj = null;
while((obj = iter.next()) != null){
// do something to obj
}
this is how NSEnumerator in Objective-C works
NSEnumerator *enumerator = // from an array
while (id obj = [enumerator nextObject]) {
// do something to obj
}
This increase the overhead of implement custom iterator
.
This also make java iterator not thread-safe. For example an ArrayList have one element in it. Two threads both ask for a same iterator for that list hasNext
at same time. Than both threads will see true
and they will invoke next
on that iterator. Because there is only one element and iterator has been asked twice which definitely will lead to an exception or error state.
I know there are thread-safe iterator but I am not sure hot it implement but I think lots blocking are happening which make it inefficient.
I think problem is that check and update are not happen atomically and I cannot understand why java designed iterator
interface like that.
Update
I see that null can be a value so my approach is invalid. But is any possible workaround to the problems I mentioned above?
Your proposition would make it impossible to have null
values in collections, since it uses null
as a "poison pill" to detect the end of the iteration.
In the very very rare cases two threads share an iterator, you just need to wrap it inside some custom class and synchronize the access to the iterator, to make the check-then-act operation atomic. This is needed anyway since, even if the iterator just had one method, the backing collection (ArrayList in your example) is not thread-safe.
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