class PositionIterator<T, P extends IPositionHolder<T, P>> implements Iterator<P> {
    private @Nullable P myIndex;
    private @Nullable P myNext;

    public PositionIterator(@NotNull P index) {
        assert index.getAnchor() != CURRENT;
        myIndex = null;
        myNext = index;
    }

    @Override
    public boolean hasNext() {
        assert myNext == null || myNext.isValid() || myNext.getAnchor() == PREVIOUS;
        return myNext != null && myNext.isValidElement();
    }

    @Override
    public P next() {<FILL_FUNCTION_BODY>}

    @Override
    public void remove() {
        if (myIndex == null)
            throw new IllegalStateException("next() has not been called");

        myIndex.remove();
    }
}

        if (myNext == null || !myNext.isValidElement()) throw new NoSuchElementException();

        myIndex = myNext.withAnchor(PositionAnchor.CURRENT);

        P oldNext = myNext;
        if (myNext.getAnchor() == PREVIOUS) {
            myNext = myNext.previousOrNull();
        } else {
            myNext = myNext.nextOrNull();
        }
        oldNext.detachListener();

        assert myNext == null || myIndex.getIndex() != myNext.getIndex();
        return myIndex;
    
<no_super_class>