OnJava8-Examples/collections/IterableClass.java

34 lines
1.0 KiB
Java
Raw Permalink Normal View History

2015-12-15 11:47:04 -08:00
// collections/IterableClass.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Anything Iterable works with for-in
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() {
2015-06-15 17:47:35 -07:00
return new Iterator<String>() {
private int index = 0;
@Override public boolean hasNext() {
2015-06-15 17:47:35 -07:00
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
*/