Iterator.forEachRemaining semantics

Brian Goetz brian.goetz at oracle.com
Sun Apr 21 10:41:31 PDT 2013


Here's a related question: if Iterator.hasNext() is false, are you 
guaranteed that the same Iterator will *never* return true again?

The most obvious condition under which the case below might be true is 
if the Consumer threw an exception.  I think its a lot to ask of all 
Iterators to wrap the invoke in a try-catch just in case one might 
throw, so it could set the iterator state to consumed there.



On 4/21/2013 12:41 PM, Arne Siegel wrote:
> Hi,
>
> the apidoc comment of Iterator.forEachRemaining says:
>
>      /**
>       * Performs the given action for each remaining element, in the order
>       * elements occur when iterating, until all elements have been processed or
>       * the action throws an exception.  Errors or runtime exceptions thrown by
>       * the action are relayed to the caller.
>       *
>       * @implSpec
>       * <p>The default implementation behaves as if:
>       * <pre>{@code
>       *     while (hasNext())
>       *         action.accept(next());
>       * }</pre>
>
>>From this it can be deduced that the following *can* be true for any implementation:
>
>      iterator.forEachRemaining(x -> null).hasNext() == false
>
>
> What about implementations that don't satisfy this condition? Can they be considered
> correct?
>
> Regards
> Arne Siegel
>


More information about the lambda-dev mailing list