Re: Improved for each loop
markspace wrote:
The difference between this and the regular for-each is that the
identifier after the colon isn't an object (not an Iterable or an array)
but an integer primitive. It should work even with literals:
for( int i : 42 ) {
.... // i == 0..41 inclusive
}
The problem here is that the syntax is slightly ambiguous on read: does
i achieve the value of 42 or not?
If you really want this feature, it's possibly right now:
public final class IteratorUtils {
public static <T> Iterable<T> getIterable(final Iterator<T> it) {
return new Iterable<T>(){public Iterator<T> iterator(){return it;}};
}
public static Iterable<Integer> range(final int high) {
return getIterable(new Iterator<Integer>() {
private int i = 0;
public boolean hasNext() { return i == high; }
public Integer next() { return i++; }
public void remove() {}
});
}
public static void main(String... args) {
for (int i : range(42)) {
System.out.println(i);
}
}
}
With Java 7 coming up, is this JSR worthy?
I believe you're looking for Project Coin (a collection of small
language changes for JDK 7), but its ultimate acceptance would be
suspect: the ability to create one's own Iterable implementations means
that it's almost trivial to roll it out, and probably easier to
understand that way, too.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth