14

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

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

在 Java 中?

4

3 回答 3

20

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

Java8之前:

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

import java.util.Iterator;

public class Range implements Iterable<Integer> {
    private int min;
    private int count;

    public Range(int min, int count) {
        this.min = min;
        this.count = count;
    }

    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            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<Integer> 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);
        }
    }

}

我希望这些会有用:)

于 2012-03-09T01:54:13.823 回答
3

Java 中没有对此的内置支持,但是您自己构建它非常容易。总的来说,Java API 提供了此类功能所需的所有位,但不会开箱即用地组合它们。

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

其他语言的 API(例如 C# 和 Python)采取了更加谨慎的观点,他们确实选择了一些使事情变得非常简单的东西,但仍然允许更深奥的组合。

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

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

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

out = file("out.txt","w")
于 2010-06-01T14:33:18.367 回答
2

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

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

然后使用迭代器获取从 min 到 max 的整数序列(都包括)

编辑

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

于 2010-06-01T14:11:36.780 回答