ArrayLists and Iterators

17. Iterator


Answer:

First Search: 4
Secnd Search: -1

Iterator

Often you wish to access the elements of an ArrayList one by one, in order. You could write a counting loop (as has been done so far in this chapter). Or, you could use an Iterator object. To get an Iterator object, use this method of ArrayList:


Iterator<E> iterator()  // Returns an iterator

ArrayList implements the Iterable interface. iterator() is the only method in this interface.

An iterator object is used to visit the elements of a list one by one. It visits only the cells that have data (so you don't need to worry about going past the end of data). This is more convenient than writing a loop. An iterator implements the  Iterator<E> interface, which has the following methods:


boolean hasNext()    // Returns true if not all elements have been visited

E next() // Returns the next element of the list,
// a reference to type E

void remove() // Remove from the list the element just returned by next()

Here is a program that prints out every element in the ArrayList:

import java.util.* ;
public class IteratorExample
{
  public static void main ( String[] args)
  {
    // Create and populate the list
    ArrayList<String> names = new ArrayList<String>();
    names.add( "Amy" );    names.add( "Bob" ); 
    names.add( "Chris" );  names.add( "Deb" ); 
    names.add( "Elaine" ); names.add( "Frank" );
    names.add( "Gail" );   names.add( "Hal" );

    // Create an iterator for the list
    Iterator<String> iter = names.iterator();

    // Use the iterator to visit each element
    while ( iter.hasNext() )
      System.out.println( iter.next() );

  }
}

Several classes in the Java libraries implement the Iterator<E> interface. Some of these classes are complicated, and a simple loop can't be used to access all their elements. For those classes, an iterator, which systematically accesses each element, is very useful.

Confusion Alert: Pay attention to the TWO interfaces:

      • Iterable interface -- a class that implements this can create an Iterator for itself.
      • Iterator<E> interface -- an Iterator implements methods to visit the elements of a list.

Question 17:

Say that a program has the following code:

    ArrayList<Integer> primes = new ArrayList<Integer>();

Assume that the list has been populated with elements. Fill in the following to create an iterator for the list:

    Iterator visitor = primes.() ;