If you want an iteration object of a class, the class must implement the Iterable interface, and then returns a Iterator instance by the iterator method.
Range Python class implements all of the usage range, such as: range (10), range (5, 10), range (10, 0, -1), range (0, 10, 2)
If we define a static factory method in the Range class, and then introduced into a static factory method, it is easier to use.
Example:
for (int X: the Range new new (10, 0, -1)) { System.out.println (X); } / * output: 10 . 9 . 8 . 7 . 6 . 5 . 4 . 3 2 . 1 * /
Code:
class Range implements Iterable<Integer> { private final int start; private final int end; private final int step; public Range(int end) { this(0, end, 1); } public Range(int start, int end) { this(start, end, 1); } public Range(int start, int end, int step) { this.start = start; this.end = end; this.step = step; } @Override public Iterator<Integer> iterator() { return new Itr(); } private class Itr implements Iterator<Integer> { int current = start; @Override public boolean hasNext() { return step > 0 ? current < end : current > end; } @Override public Integer next() { int t = current; current += step; return t; } } }