Not to mention what I propose, this is the only and best solution, but it is general enough to be reusable, safe for text and allowing you to break early during your crawl.
You can easily expand it and make it common to any type of collection.
Simple trace implementation
The implementation consists of:
- a reusable class of type Actor for defining actions (if any),
- reusable safety class,
- , .
, , , .
Actor
interface Actor<T> {
void act(final T element) throws TraversalInterruptionException;
}
Traversal
class Traversal<T> {
int index = 0;
Actor<T> actor = null;
public Traversal(final Actor<T> a) {
actor = a;
}
void traverse(final List<T> col) {
if (index < col.size()) {
final T element = col.get(index++);
try {
if (actor != null) {
actor.act(element);
}
traverse(col);
} catch (final TraversalInterruptionException e) {
index = 0;
}
} else {
index = 0;
}
}
}
TraversalInterruptionException
class TraversalInterruptionException extends Exception {
}
@Test
public void test() {
final List<String> list = new ArrayList<String>();
final Traversal<String> strTraversal = new Traversal<String>(new Actor<String>() {
@Override
public void act(final String element)
throws TraversalInterruptionException {
if ("exit".equals(element)) {
throw new TraversalInterruptionException();
}
System.out.println(element);
}
});
list.add("test1");
list.add("test2");
list.add("test3");
list.add("exit");
list.add("test4");
strTraversal.traverse(list);
strTraversal.traverse(list);
}
test1
test2
test3
test1
test2
test3