In Java how to traverse an ArrayList without using any looping constructs ?
You could use recursion.
public void doSomethingToAll(List list)
{
// Begin the recursion.
doSomethingToAll(list, 0);
}
private void doSomethingToAll(List list, int index)
{
// Break the recursion when we have processed the entire list.
if (index >= list.size()) return;
// Do whatever you want with the list.
process(list.get(index));
// Recursive step. Process the next element.
doSomethingToAll(list, index + 1);
}
Not saying what I offer is the only and the best solution, but it's generic enough to be reused easily, type-safe, and allows you to break early in the course of your traversal.
You can easily extend it and make it generic to any type of collection.
The implementation is composed of:
By reusable I mean that once used on a collection you can reuse it without needing to reinstantiate it, so that you only need one instance per target behavior.
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) {
/* let's get out of there early */
index = 0; // reset
}
} else {
index = 0; // reset
}
}
}
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); // and again to test the reset
}
test1
test2
test3
test1
test2
test3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With