Re: Improved for each loop
Joshua Cranmer wrote:
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) {
This is a clever idea. I'll try this and see if it helps. BTW, I think
your test in hasNext() is incorrect. It should be !=, not ==, or maybe
<= or <, which will catch problems if the user calls next() too many
times and increments I over the bound.
My version is at the end of this post.
I believe you're looking for Project Coin (a collection of small
Thanks again, I'll take a look at that.
Code follows:
package local.itorutils;
import java.util.Iterator;
public class Iterators {
private Iterators() {}
/**
* Returns an Iterable that counts from 0 up to, but not including, the
* bound.
* @param bound Upper bound, exclusive, for this Iterable.
* @return An Iterable which counts 0..bound-1 inclusive.
*/
public static Iterable<Integer> rangeX( final int bound ) {
return makeNewIterable( new Iterator<Integer>() {
int i;
@Override
public boolean hasNext() { return i < bound; }
@Override
public Integer next() { return i++; }
@Override
public void remove() {
throw new UnsupportedOperationException(
"Not supported." );
}
} );
}
/**
* Returns an Iterable that counts from 0 up to and including the
* bound.
* @param bound Upper bound, inclusive, for this Iterable.
* @return An Iterable which counts 0..bound inclusive.
*/
public static Iterable<Integer> rangeI( final int bound ) {
return makeNewIterable( new Iterator<Integer>() {
int i;
@Override
public boolean hasNext() { return i <= bound; }
@Override
public Integer next() { return i++; }
@Override
public void remove() {
throw new UnsupportedOperationException(
"Not supported." );
}
} );
}
private static Iterable<Integer> makeNewIterable( final
Iterator<Integer> it ) {
return new Iterable<Integer>( ) {
@Override
public Iterator<Integer> iterator() {
return it;
}
};
}
}