代码之家  ›  专栏  ›  技术社区  ›  Simon

在Java中是否有类似枚举的范围(x,y)?

  •  10
  • Simon  · 技术社区  · 15 年前

    有类似c/.net的东西吗

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

    在Java中?

    3 回复  |  直到 11 年前
        1
  •  16
  •   Ebrahim Byagowi    11 年前

    编辑:作为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();
                }
            };
        }
    }
    

    例如,可以通过以下方式使用范围:

    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);
            }
        }
    
    }
    

    希望这些有用:)

        2
  •  3
  •   Tendayi Mawushe    15 年前

    在Java中没有内置的支持 不过,你自己动手很容易。大体上,Java API提供了这种功能所需的所有位,但不能将它们组合在框外。

    Java采用的方法有无限多的方式来组合事物,所以为什么特权比其他组合少一些。使用正确的构建块集,可以轻松地构建其他所有内容(这也是Unix的理念)。

    其他语言的api(例如c和python)采用了一种更为精确的视图,它们确实选择了一些东西使其变得非常简单,但仍然允许更深奥的组合。

    Java方法中的问题的一个典型例子可以在 Java IO 图书馆。为输出创建文本文件的标准方法是:

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

    Java IO库使用 Decorator Pattern 哪一个对于灵活性来说真的是一个好主意,但确实比不需要缓冲文件更频繁?将其与Python中的等价物进行比较,这使得典型的用例非常简单:

    out = file("out.txt","w")
    
        3
  •  2
  •   Andreas Dolk    15 年前

    您可以将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和自定义迭代器的自定义可枚举类(但现在不在这里;)。

    推荐文章