Creating Iterable Objects: using a for-each for loop on an Iterable object : Iterable Interface « Collections « Java Tutorial





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

// This class supports iteration of the 
// characters that comprise a string.
class IterableString implements Iterable<Character>, Iterator<Character> {
  private String str;

  private int count = 0;

  public IterableString(String s) {
    str = s;
  }
  // The next three methods implement Iterator.
  public boolean hasNext() {
    if (count < str.length()){
      return true;
    }  
    return false;
  }

  public Character next() {
    if (count == str.length())
      throw new NoSuchElementException();

    count++;
    return str.charAt(count - 1);
  }

  public void remove() {
    throw new UnsupportedOperationException();
  }

  // This method implements Iterable.
  public Iterator<Character> iterator() {
    return this;
  }
}

public class MainClass {
  public static void main(String args[]) {
    IterableString x = new IterableString("This is a test.");

    for (char ch : x){
      System.out.println(ch);
    }
  }
}
T
h
i
s
 
i
s
 
a
 
t
e
s
t
.










9.36.Iterable Interface
9.36.1.Using an Iterator
9.36.2.Iterable interface: while loop and for loop
9.36.3.'for' statement for Iterable object in JDK 5 has been enhanced.
9.36.4.Creating Iterable Objects: using a for-each for loop on an Iterable object