Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to traverse an ArrayList without using looping constructs?

Tags:

java

In Java how to traverse an ArrayList without using any looping constructs ?

like image 869
Mariselvam Avatar asked Jan 20 '23 23:01

Mariselvam


2 Answers

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);
}
like image 177
Reese Moore Avatar answered Jan 30 '23 20:01

Reese Moore


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.


A Simple Traversal Implementation

The implementation is composed of:

  • a reusable type-safe Actor class to define actions (if any),
  • a reusable type-safe Traversal class,
  • and an exception class used to break out early of a traversal.

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 It

  @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
  }

Output

test1
test2
test3
test1
test2
test3
like image 24
haylem Avatar answered Jan 30 '23 18:01

haylem