OnJava8-Examples/holding/IterableClass.java

31 lines
869 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: holding/IterableClass.java
// Anything Iterable works with foreach.
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(" ");
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public Iterator<String> iterator() {
return new Iterator<String>() {
private int index = 0;
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public boolean hasNext() {
return index < words.length;
}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public String next() { return words[index++]; }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
for(String s : new IterableClass())
System.out.print(s + " ");
}
} /* Output:
And that is how we know the Earth to be banana-shaped.
*///:~