如何实现这个FilteringIterator?

Leo*_*eon 9 java iterator

  1. IObjectTest是一个具有单个布尔测试(Object o)方法的接口

  2. FilteringIterator是迭代器的实现,其与另一个迭代器和一个IObjectTest实例初始化:新FilteringIterator(myIterator,MYTEST).然后,您的FilteringIterator将允许迭代'myIterator',但跳过任何未通过'myTest'测试的对象.

由于"hasNext"操作实际上涉及重复移动底层迭代器,直到到达下一个匹配项.问题是如何将it迭代器移回迭代器,因为hasNext不应该移动底层迭代器.

Roe*_*ker 10

如果你想自己做,你可以使用类似于我在下面写的代码.但是,我建议您使用Guava的Iterators.filter(Iterator,Predicate)

public class FilteredIterator<T> implements Iterator<T> {
    private Iterator<? extends T> iterator;
    private Filter<T> filter;
    private T nextElement;
    private boolean hasNext;

    /**
     * Creates a new FilteredIterator using wrapping the iterator and returning only elements matching the filter.
     * 
     * @param iterator
     *            the iterator to wrap
     * @param filter
     *            elements must match this filter to be returned
     */
    public FilteredIterator(Iterator<? extends T> iterator, Filter<T> filter) {
        this.iterator = iterator;
        this.filter = filter;

        nextMatch();
    }

    @Override
    public boolean hasNext() {
        return hasNext;
    }

    @Override
    public T next() {
        if (!hasNext) {
            throw new NoSuchElementException();
        }

        return nextMatch();
    }

    private T nextMatch() {
        T oldMatch = nextElement;

        while (iterator.hasNext()) {
            T o = iterator.next();

            if (filter.matches(o)) {
                hasNext = true;
                nextElement = o;

                return oldMatch;
            }
        }

        hasNext = false;

        return oldMatch;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

public interface Filter<T> {

    /**
     * Determines whether elements should be filtered or not.
     * 
     * @param element the element to be matched against the filter
     * @return {@code true} if the element matches the filter, otherwise {@code false}
     */
    public boolean matches(T element);
}
Run Code Online (Sandbox Code Playgroud)

  • 我很确定`remove` 方法是行不通的。它将删除下一个元素,而不是当前元素。 (2认同)

Mar*_*ers 5

你需要使你的迭代器有状态.缓存从中检索的最后一个值,hasNext并使用该next方法中的值(如果存在).

private boolean hasCached;
private T cached;

public boolean hasNext() {
   if ( hasCached ) return true;
   //iterate until you find one and set hasCached and cached
}

public T next() {
   if ( hasCached ) {
      hasCached = false;
      return cached;
   }
   //iterate until next matches
}
Run Code Online (Sandbox Code Playgroud)


Sea*_*oyd 5

如果这是家庭作业,这对您没有帮助,但如果不是:Guava 库具有您想要的确切功能

Iterators.filter(Iterator, Predicate)

(你可以看看他们是如何做到的以获得灵感)