For loop - like Python range function

后端 未结 9 1514
情歌与酒
情歌与酒 2020-12-30 21:45

I was wondering if in Java there is a function like the python range function.

range(4)

and it would return

[0,1,2,3]
         


        
9条回答
  •  离开以前
    2020-12-30 22:40

    Without an external library, you can do the following. It will consume significantly less memory for big ranges than the current accepted answer, as there is no array created.

    Have a class like this:

    class Range implements Iterable {
    
        private int limit;
    
        public Range(int limit) {
            this.limit = limit;
        }
    
        @Override
        public Iterator iterator() {
            final int max = limit;
            return new Iterator() {
    
                private int current = 0;
    
                @Override
                public boolean hasNext() {
                    return current < max;
                }
    
                @Override
                public Integer next() {
                    if (hasNext()) {
                        return current++;   
                    } else {
                        throw new NoSuchElementException("Range reached the end");
                    }
                }
    
                @Override
                public void remove() {
                    throw new UnsupportedOperationException("Can't remove values from a Range");
                }
            };
        }
    }
    

    and you can simply use it like this:

        for (int i : new Range(5)) {
            System.out.println(i);
        }
    

    you can even reuse it:

        Range range5 = new Range(5);
    
        for (int i : range5) {
            System.out.println(i);
        }
        for (int i : range5) {
            System.out.println(i);
        }
    

    As Henry Keiter pointed out in the comment below, we could add following method to the Range class (or anywhere else):

    public static Range range(int max) {
        return new Range(max);
    }
    

    and then, in the other classes we can

    import static package.name.Range.range;
    

    and simply call

    for (int i : range(5)) {
        System.out.println(i);
    }
    

提交回复
热议问题