Iterator

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

4
-1

Iterator

It is common for a program to access the elements of an ArrayList one by one, in order. This can be done using a counting loop (as has been done so far this chapter). However, an Iterator object may also be used. To get an Iterator object for a ArrayList use this method:

Iterator iterator()  // Returns an iterator

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

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

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

E next()             // Returns the next element of the list. 

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.* ;
class IteratorExample
{
  public static void main ( String[] args)
  {
    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" );

    Iterator<String> iter = names.iterator();

    while ( iter.hasNext() )
      System.out.println( iter.next() );

  }
}

Several classes in the Java libraries implement the Iterator<E> interface. Some classes are complicated, and a simple loop can't be used to access all their elements. For those classes, an iterator can be used to access the elements.

QUESTION 17:

Would it be convenient to access all the elements of an ArrayList without setting up an iterator?