mardi 31 mars 2020

Solution: Iterator which doesn't know if it has a next element

I wrote an iterator, which returns subgraphs of a fixed size of another given undirected simple graph. It maintains an internal graph which is the currently calculated subgraph and has private stacks and lists from which it calculates the next subgraph.

It is not possible to know if the iterator can return another element, because maybe the algorithm terminates when trying to find the next subgraph.

In this design, the pattern of next() and hasNext() which Java offers doesn't work out. I currently wrote my own Interface BlindIterator with the following abstract methods:

 /**
 * @return True iff the current element is a valid return.
 */
public boolean hasCurrent();

/**
 * @return Returns the current element, but does NOT generate the next element. This method can be called


 * as often as wanted, without any side-effects.
 */
public T getCurrent();

/**Generates the next element, which can then be retrieved with getCurrent(). This method thus only provides
 * this side-effect. If it is called while the current element is invalid, it may produce and exception,
 * depending on the implementation on the iterator.
 */
public void generateNext();

Is this a common pattern and are there better designs than mine?

Aucun commentaire:

Enregistrer un commentaire