static final Iterable<Character> alphabet() {
return new Iterable<Character>() {
public final Iterator<Character> iterator() {
return new Iterator<Character>() {
private char cursor = 'A';
public boolean hasNext() {
return cursor <= 'Z';
}
public Character next() {
return cursor++;
}
public void remove() {
throw new UnsupportedOperationException("cannot remove from stream");
}
};
}
};
}
使用法:
for (final char ch : alphabet()) {
/* ch in interval [A,Z] */
}
これがより一般的な形式です。
static final Iterable<Character> iterable(final CharSequence seq) {
return new Iterable<Character>() {
public final Iterator<Character> iterator() {
return new Iterator<Character>() {
private int cursor;
public boolean hasNext() {
return cursor < seq.length();
}
public Character next() {
return seq.charAt(cursor++);
}
public void remove() {
throw new UnsupportedOperationException("cannot remove from stream");
}
};
}
};
}
/* ... */
for (final char ch : iterable("qwertyuiop")) {
/* ... */
}