// RepeatString.,ava // Demonstrates the use of an iterator to generate a potentially // infinite sequence. // // If you define an object w of class RepeatString with argument s and then // create an iterator for w, the iterator will first return s, then // s+s then S+s+s etc. import java.util.Iterator; public class RepeatString implements Iterable { public String w; // String to be repeated public RepeatString(String w) { // Constructor this.w = w; } public Iterator iterator() { Iterator ic = new Iterator() { private String s = ""; // current state public boolean hasNext() { return true; } public String next() { s = s+w; return s; } public void remove() { } // stub }; return ic; } public static void main(String[] args) { RepeatString w = new RepeatString("a"); Iterator ic = w.iterator(); for (int i=0; i < 10; i++) System.out.print(ic.next() + " "); System.out.println(); } }