Examples of for-each loops on Iterable objects and behind-the-scenes of a for-each loop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
public class IterableExamples {
/**
* @param args
*/
public static void main(String[] args) {
/********** Examples of for-each loop *********/
/*** Any object that implements Iterable<E> can be
used in a for-each loop with the element type E ****/
ArrayList<Integer> numbers = new ArrayList<Integer>();
//initialize the array list to integers 0 to 9
for (int i = 0; i < 10; ++i){
numbers.add(i);
}
// printing the ArrayList in a for-each loop
System.out.println("The array list:");
for (Integer element: numbers) {
System.out.print(element + " ");
}
System.out.println(); // print new line
// adding all array list elements in a for-each loop:
int sum = 0;
for (Integer element: numbers) {
sum += element;
}
System.out.println("The sum of all elements is " + sum);
Stack<Integer> numStack = new Stack<Integer>();
// pushing all elements of the array list onto the stack
for (Integer element: numbers) {
numStack.push(element);
}
// printing the stack in a for-each loop:
System.out.println("The stack:");
for (Integer element: numStack) {
System.out.print(element + " ");
}
System.out.println(); // print new line
// Behind the scenes of a for-each loop.
// This loop is equivalent to the sum loop above
sum = 0;
Iterator<Integer> theIterator = numbers.iterator();
while (theIterator.hasNext()) {
sum = sum + theIterator.next();
}
System.out.println("The sum of all elements is " + sum);
}
}
A somewhat artificial example: making a string iterable.
/**
A string that can be iterated character by character
in a for-each loop
**/
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 characters 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();
}
}
}
Another example: Fibonacci iterator.
/**
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 the 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();
}
}
}
Testing code for InterableString and Fibonacci.
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);
}
// 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);
}
}
}