Given a class named Range. It represents a range from A (inclusive) to B (exclusive). The class implements the interface Iterable, therefore, an instance of Range can be used in the for-each loop.
Write a body of the overridden method iterator so that the following code works correctly:
Range range = new Range(2, 6);
for (Long val : range) {
System.out.println(val);
}
It must print:
2
3
4
5
Report a typo
Sample Input 1:
2 6
Sample Output 1:
2
3
4
5
import java.util.Iterator;
class Range implements Iterable<Long> {
private long fromInclusive;
private long toExclusive;
public Range(long from, long to) {
this.fromInclusive = from;
this.toExclusive = to;
}
@Override
public Iterator<Long> iterator() {
// write your code here
return new Iterator<Long>() {
private long current = fromInclusive;
@Override
public boolean hasNext() {
return current < toExclusive;
}
@Override
public Long next() {
return current++;
}
};
}
}
Iterator and Iterable Iterable range
原文:https://www.cnblogs.com/longlong6296/p/13744612.html