Iterable range

Report a typo

In this problem you need to create your own iterator but the theory has not given an example for it. You may skip the problem or google how to do that. Actually, the problem is not complicated.

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

Sample Input 1:

2 6

Sample Output 1:

2
3
4
5
Write a program in Java 17
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
}
}
___

Create a free account to access the full topic