此实现没有内存占用.
/** * @param begin inclusive * @param end exclusive * @return list of integers from begin to end */ public static Listrange(final int begin, final int end) { return new AbstractList () { @Override public Integer get(int index) { return begin + index; } @Override public int size() { return end - begin; } }; }
在Java 8中,您可以简单地说:
IntStream.range(begin, end).iterator() // returns PrimitiveIterator.OfInt
或者如果您需要盒装版本:
IntStream.range(begin, end).boxed().iterator() // returns Iterator
未经测试.将其映射到"min,count"是留给读者的练习.
public class IntRangeIterator implements Iterator{ private int nextValue; private final int max; public IntRangeIterator(int min, int max) { if (min > max) { throw new IllegalArgumentException("min must be <= max"); } this.nextValue = min; this.max = max; } public boolean hasNext() { return nextValue <= max; } public Integer next() { if (!hasNext()) { throw new NoSuchElementException(); } return Integer.valueOf(nextValue++); } public void remove() { throw new UnsupportedOperationException(); } }
如果你真的想要最短的代码量,那么Bombe的答案就可以了.然而,它没有充分理由吸引记忆.如果你想自己实现它,它将是这样的:
import java.util.*; public class IntegerRange implements Iterator{ private final int start; private final int count; private int position = -1; public IntegerRange(int start, int count) { this.start = start; this.count = count; } public boolean hasNext() { return position+1 < count; } public Integer next() { if (position+1 >= count) { throw new NoSuchElementException(); } position++; return start + position; } public void remove() { throw new UnsupportedOperationException(); } }
使用番石榴框架的一个例子.请注意,这不会实现集合(尽管您必须阅读ContiguousSet实现以验证它).
import com.google.common.collect.ContiguousSet; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.DiscreteDomains; class RangeIterator { public Iteratorrange(int start, int length) { assert length > 0; Range dim_range = Ranges.closedOpen(start, start + length); DiscreteDomain ints = DiscreteDomains.integers(); ContiguousSet dim = dim_range.asSet(ints); return dim.iterator(); } }