loops - how to iterate on every second element in java -
i tried work out couldn't.
i need implement class implements iterator , takes iterator constructor parameter,
1)need return every 2nd hasnext
2)need return every 2nd next element
basically trying make use of given iterator received constructor, when use next element on hasnext increasing iterator 1 element. problem comes when independently access hasnext or next element , not pass test cases. solution or idea on this
template , expected implementation looks below:
public class alternateiterator<t> implements iterator<t> public alternateiterator(iterator<t> target) public boolean hasnext() { boolean returnvalue = false; if(iterator.hasnext()) { iterator.next(); returnvalue = iterator.hasnext(); } return returnvalue; } @override public t next() { t object = null; if(iterator.hasnext()) { object = iterator.next(); return object; } else return null;
-- gone through link creates new implementation while want use given template only:
track whether you've skipped element source iterator or not, this:
import java.util.iterator; import java.util.nosuchelementexception; import java.util.objects; final class alternateiterator<t> implements iterator<t> { static <t> iterable<t> alternate(iterable<t> original) { return () -> new alternateiterator<>(original.iterator()); } private final iterator<t> source; private boolean skipped; alternateiterator(iterator<t> source) { this.source = objects.requirenonnull(source); } @override public boolean hasnext() { if (!skipped) { if (source.hasnext()) source.next(); skipped = true; } return source.hasnext(); } @override public t next() { if (hasnext()) { skipped = false; return source.next(); } throw new nosuchelementexception(); } @override public void remove() { source.remove(); } }
Comments
Post a Comment