Compound iterator implementation
The compound iterator follows the bridge design pattern. It uses a behavior that contains the base iterator, the subiterator, and the function composeItems. Furthermore, the behavior contains a factory method for creating the so-specified compound iterator.
Any behavior of a compound iterator extends the abstract class CompoundIteratorBehavior that requires methods baseIterator, subIterator and composeItems. Furthermore, the class CompoundIteratorBehavior contains the factory method iterator that creates the so-specified compound iterator.
public abstract class CompoundIteratorBehavior<BaseType, SubType, CompoundType>
{
public abstract Iterator<BaseType> baseIterator();
public abstract Iterator<SubType> subIterator(BaseType x0);
public abstract CompoundType composeItems(BaseType x0, SubType x1);
public Iterator<CompoundType> iterator()
{
return new CompoundIterator<BaseType, SubType, CompoundType>(this);
}
}
In the following, the implementation of the compound iterator is given.
public class CompoundIterator<BaseType, SubType, CompoundType>
implements Iterator<CompoundType>
{
private CompoundIteratorBehavior<BaseType, SubType, CompoundType> behavior;
private boolean hasnext;
private Iterator<BaseType> it0;
private Iterator<SubType> it1;
private BaseType x0;
private CompoundType x01;
public CompoundIterator(CompoundIteratorBehavior<BaseType, SubType, CompoundType> behavior)
{
this.behavior=behavior;
hasnext=true;
it0=behavior.baseIterator();
x01=tryNext0();
}
public boolean hasNext()
{
return hasnext;
}
public CompoundType next()
{
CompoundType x=x01;
x01=tryNext1();
return x;
}
private CompoundType tryNext0()
{
while (it0.hasNext())
{
x0=it0.next();
if (x0!=null)
{
it1=behavior.subIterator(x0);
return tryNext1();
}
}
hasnext=false;
return null;
}
private CompoundType tryNext1()
{
if (it1.hasNext())
return behavior.composeItems(x0, it1.next());
else
return tryNext0();
}
}
Next: [Usage of the compound iterator] or
[up]
H.W. Lang mail@hwlang.de Impressum Datenschutz
Created: 05.02.2008 Updated: 18.02.2023