Java exceptions contract of Iterator remove -
i'm implementing iterator utilises iterator, of not know, whether supports remove()
method or not.
consider following edge case: underlying iterator not support remove()
, iterator next()
has not yet been called.
do violate interface contract, if remove()
throws – in situation – illegalstateexception
instead of unsupportedoperationexception
?
(as next()
called, underlying remove()
can called, throw appropriate unsupportedoperationexception
.)
if so, how refactor code check whether underlying iterator supports remove()
or not?
an example:
<t> iterator<t> getsetviewiterator(collection<t> collection) { iterator<t> uniqueitr = new hashset<>(collection).iterator(); return new iterator<t>() { private t current = null; private boolean hasremoved = true; @override public boolean hasnext() { return uniqueitr.hasnext(); } @override public t next() { if(!hasnext()) throw new nosuchelementexception(); hasremoved = false; return current = uniqueitr.next(); } @override public void remove() { if(hasremoved) throw new illegalstateexception(); for(iterator<t> iterator = collection.iterator(); iterator.hasnext();) { if(iterator.next().equals(current)) iterator.remove(); } hasremoved = true; } }; }
(for our purposes can assume, passed collection not contain null
.)
per documentation linked to, both exceptions acceptable remove
method, , situation of calling remove
prior next
explicitly mentioned, , allows throwing illegalstateexception
.
for iterator not support remove
, throwing unsupportedoperationexception
valid throwing illegalstateexception
in illegal states (remove
before next
, second remove
after next
), , throwing other exception in valid states (first remove
after next
). both exceptions applicable call in invalid state - because state invalid , operation unsupported.
your wrapping iterator works right - checks invalid state, , delegates inner iterator, may throw unsupported operation exception. iterator not need know whether inner iterator supports remove because, noted above, in illegal state both exceptions valid responses.
Comments
Post a Comment