Java iterators examples.

Iterable strings -- strings that you can access in an enhanced 'for' loop (a.k.a. for-each loop).


/**
A string that can be iterated character by character
**/

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IterableString implements Iterable<Character> {
    private String thestring;

    /**
     * Creates a new IterableString
     * @param string -- the string data
     **/    
    public IterableString(String string) {
	thestring = string;
    }

    /**
     * Returns an iterator for the string that iterates 
     * character by character
     **/
    public Iterator<Character> iterator() {
	return new StringIterator();
    }

    // the iterator is a private inner class
    private class StringIterator implements Iterator<Character> {
	private int position = 0;

	/**
	* @return - true if there are more characters in the string,
	* false otherwise
	**/
	public boolean hasNext() {
	    return position < thestring.length();
	}

	/**
	* @return - the next charcaters in the string
	* @throws  NoSuchElementException when past the last character
	**/
	public Character next() {
	    if (position < thestring.length()) {
		Character current = thestring.charAt(position);
		++position;
		return current;
	    } else {
		throw new NoSuchElementException();
	    }
	}

	/**
	 * method not supported
	 **/
	public void remove() {
	    throw new UnsupportedOperationException();
	}
    }
}

Testing class for Iterable strings and the next example (iterable Fibonacci numbers).


import java.util.Iterator;

public class TestIterable {
    public static void main(String [] args) {
	IterableString testString1 = new IterableString("Hi there!");

	System.out.println("Printing a string \"Hi there!\" in a for-each loop");

	for (char c: testString1) {
	    System.out.println(c);
	}

	IterableString testString2 = new IterableString("");

	System.out.println("Printing an empty string in a for-each loop");	
	for (char c: testString2) {
	    System.out.println(c);
	}

	IterableString testString3 = new IterableString("Hello");
	System.out.println("Printing a string \"Hello\" in an iterator loop");
	// behind-the-scenes of a for-each loop
	Iterator<Character> iter =  testString3.iterator();
	while (iter.hasNext()) {
	    char c = iter.next();
	    System.out.println(c);
	}

	// an iterator that produces up to n-th fibonacci numbers (start at 0)
	IterableFibonacci fibNumbers = new IterableFibonacci(15);

	System.out.println("Fibonacci numbers up to n = 15");
	for (int fib: fibNumbers) {
	    System.out.println(fib);
	}
	
	System.out.println("Fibonacci numbers up to n = 10");
	fibNumbers.setMaxIndex(10);
	for (int fib: fibNumbers) {
	    System.out.println(fib);
	}
	
    }
}

Starting code for IterableFibonacci:


/**
The class implements Iterable Fibonacci numbers, i.e. 
Fibonacci numbers that can be produced in a for-each
(enhanced for) loop. 

Fibonacci numbers are a sequence of numbers defined as 
follows:
F(0) = 0, F(1) = 1, F(k) = F(k-1) + F(k -2) for k > 1.

For more on Fibonacci numbers see
http://en.wikipedia.org/wiki/Fibonacci_number

The parameter maxIndex in the constructor sets the 
last index in teh sequence. It can be reset using
setMaxIndex method. 
**/

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IterableFibonacci implements Iterable<Integer> {
    private int maxIndex;

    /**
     * Creates a new IterableFibonacci
     * @param maxIndex -- the index of the last Fibonacci number returned 
     * in this sequence
     * @throws IllegalArgumentException if maxIndex < 0
     **/
    public IterableFibonacci(int maxIndex) {
	if (maxIndex < 0) {
	    throw new IllegalArgumentException("Invalid index for Fibonacci" +
					       "sequence: "  + maxIndex);
	}
	this.maxIndex = maxIndex;
    }

    /**
     * sets the maximal index in this Fibonacci sequence 
     * @param newMax -- the new value of the maximum index 
     * in this sequence
     * @throws IllegalArgumentException if newMax < 0
     **/
    public void setMaxIndex(int newMax) {
	if (newMax < 0) {
	    throw new IllegalArgumentException("Invalid index for Fibonacci" +
					       "sequence: "  + newMax);
	}
	maxIndex = newMax;
    }

    /**
     * Returns an iterator that produces the sequence of Fibonacci 
     * numbers from index 0 to the maximum index (inclusive)
     **/
    public Iterator<Integer> iterator() {
	return new FibonacciIterator();
    }

    private class FibonacciIterator implements Iterator<Integer> {
	// two latest fibonacci numbers:
	private int fib1 = 0;
	private int fib2 = 1;

	/**
	* @return - true if there are more elements in the sequence,
	* false otherwise
	**/
	public boolean hasNext() {
	    return false; // this is just a stub, replace with your code
	}

	/**
	* @return - the next Fibonacci number in the sequence
	* @throws -- FILL THIS IN
	**/
	public Integer next() {
	    return 0;  // this is just a stub, replace with your code
	}

	/**
	 * method not supported
	 **/
	public void remove() {
	    throw new UnsupportedOperationException();
	}
    }
}

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.