如何实现这个FilteringIterator? [英] How to implement this FilteringIterator?

查看:139
本文介绍了如何实现这个FilteringIterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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

  1. IObjectTest is a interface with a single boolean test(Object o) method

FilteringIterator是Iterator的一个实现,它是用另一个Iterator
和一个IObjectTest实例初始化的
:new
FilteringIterator(myIterator,
myTest)。您的FilteringIterator将为
然后允许迭代超过
'myIterator',但跳过任何未通过
'myTest'测试的
对象。

FilteringIterator is an implementation of Iterator which is initialized with another Iterator and an IObjectTest instance: new FilteringIterator(myIterator, myTest). Your FilteringIterator will then allow iteration over 'myIterator', but skipping any objects which don't pass the 'myTest' test.

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

Since the "hasNext" operation actually involve repeatly moving the underlying iterator untill reach the next matching item. The question is how can it move it iterator back since hasNext is not supposed to move the underlying iterator.

推荐答案

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

You would need to make your iterator stateful. Cache the last value you retrieved from hasNext and use that from the next method, if it exists.

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
}

这篇关于如何实现这个FilteringIterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆