2015-09-07 11:44:36 -06:00
|
|
|
|
// containers/IterableClass.java
|
2015-06-15 17:47:35 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-09-07 11:44:36 -06:00
|
|
|
|
// Anything Iterable works with forEach.
|
2015-06-15 17:47:35 -07:00
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
|
|
public class IterableClass implements Iterable<String> {
|
|
|
|
|
protected String[] words = ("And that is how " +
|
|
|
|
|
"we know the Earth to be banana-shaped.").split(" ");
|
|
|
|
|
@Override
|
|
|
|
|
public Iterator<String> iterator() {
|
|
|
|
|
return new Iterator<String>() {
|
|
|
|
|
private int index = 0;
|
|
|
|
|
@Override
|
|
|
|
|
public boolean hasNext() {
|
|
|
|
|
return index < words.length;
|
|
|
|
|
}
|
|
|
|
|
@Override
|
|
|
|
|
public String next() { return words[index++]; }
|
|
|
|
|
@Override
|
|
|
|
|
public void remove() { // Not implemented
|
|
|
|
|
throw new UnsupportedOperationException();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
for(String s : new IterableClass())
|
|
|
|
|
System.out.print(s + " ");
|
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
|
}
|
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
|
And that is how we know the Earth to be banana-shaped.
|
2015-09-07 11:44:36 -06:00
|
|
|
|
*/
|