在Java中有类似Enumerable.Range(x,y)的东西吗?

有没有类似C#/ .NET的东西

IEnumerable range = Enumerable.Range(0, 100); //.NET 

在Java?

编辑:作为Java 8,这可以通过java.util.stream.IntStream.range(int startInclusive, int endExclusive)

在Java8之前:

在Java中没有这样的东西,但你可以有这样的东西:

 import java.util.Iterator; public class Range implements Iterable { private int min; private int count; public Range(int min, int count) { this.min = min; this.count = count; } public Iterator iterator() { return new Iterator() { private int cur = min; private int count = Range.this.count; public boolean hasNext() { return count != 0; } public Integer next() { count--; return cur++; // first return the cur, then increase it. } public void remove() { throw new UnsupportedOperationException(); } }; } } 

例如,您可以通过这种方式使用Range:

 public class TestRange { public static void main(String[] args) { for (int i : new Range(1, 10)) { System.out.println(i); } } } 

此外,如果您不喜欢直接使用new Range(1, 10) ,可以使用工厂类:

 public final class RangeFactory { public static Iterable range(int a, int b) { return new Range(a, b); } } 

这是我们的工厂测试:

 public class TestRangeFactory { public static void main(String[] args) { for (int i : RangeFactory.range(1, 10)) { System.out.println(i); } } } 

我希望这些有用:)

在Java中没有内置的支持 ,但是自己构建它非常容易。 总的来说,Java API提供了这种function所需的所有function,但不能将它们组合在一起。

Java采用的方法是有无数种方法来组合事物,所以为什么要优先考虑一些组合而不是其他组合。 使用正确的构建块,其他所有内容都可以轻松构建(这也是Unix哲学)。

其他语言API(例如C#和Python)采用更加严格的视图,他们确实选择了一些非常简单的东西,但仍允许更多深奥的组合。

可以在Java IO库中看到Java方法问题的典型示例。 为输出创建文本文件的规范方法是:

 BufferedWriter out = new BufferedWriter(new FileWriter("out.txt")); 

Java IO库使用了Decorator模式 ,这对于灵活性来说是一个非常好的主意,但是通常你需要一个缓冲文件吗? 将它与Python中的等价物进行比较,这使得典型用例非常简单:

 out = file("out.txt","w") 

您可以将Arraylist子类化以实现相同的目标:

 public class Enumerable extends ArrayList { public Enumerable(int min, int max) { for (int i=min; i<=max; i++) { add(i); } } } 

然后使用迭代器从最小到最大获取整数序列(包括)

编辑

正如sepp2k所提到的 - 上面的解决方案快速,肮脏且实用,但有一些严重的退出(不仅O(n)在空间,而它应该有O(1))。 为了更严格地模拟C#类,我宁愿编写一个实现Iterable和自定义迭代器的自定义Enumerable类(但不是这里和现在;))。