Thursday, May 19, 2011

Iterating over ArrayList in java

To get successive elements from an ArrayList, there are 4 ways:

Use either a for loop with an integer index to get all the elements from an ArrayList, or go over all elements in a ArrayList using an Iterator (forward) or ListIterator (forward / backward).
  1. foreach loop. This is fast and works for all kinds of lists, but is not entirely flexible (only sequential forward with no deletions, additions, or multiple references). This should be your first choice in programming. Works efficiently with both ArrayList and LinkedList.
    ArrayList<String> a = new ArrayList<String>();
    . . .
    for (String s : a) {
    System.out.println(s);
    }

     

  2. for loop with index. This is fast, but should not be used with a LinkedList. It does allow orders other than sequentially forward by one.

    for (int i = 0; i < a.size(); i++) {
    System.out.println(a.get(i));
    }

     

  3. Iterator<E> - Allows simple forward traversal. Can be used for the largest number of other kinds of data structures. This example uses an Iterator to print all elements (Strings) in an ArrayList. It uses hasNext(), which returns true if there are more elements, and next(), which returns the next element. Works with both ArrayList and LinkedList.

    for (Iterator<String> iter = a.iterator(); iter.hasNext();) 
    {
    System.out.println(iter.next());
    }


  4. ListIterator<E> - Allows traversal of the ArrayList, but it is more general than a simple Iterator, allowing inserts and deletes (although both are very slow for an ArrayList). It also allows bidirectional traversal. Works efficiently with both ArrayList and LinkedList.

No comments:

Post a Comment

Chitika