Java – how do I implement this filteringitator?

>Iobjecttest is an interface

Because the "has next" operation actually involves repeatedly moving the underlying iterator until the next matching item is reached The problem is how to iterate it back, because hasnext should not move the underlying iterator

Solution

You need to make your iterator stateful Cache the last value retrieved from hasnext and use the next method, if any

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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>