Populating a List with a contiguous range of integers

前端 未结 4 1956
耶瑟儿~
耶瑟儿~ 2020-12-14 15:12

I\'d like to have a list which contains the integers in the range 1 to 500. Is there some way to create this list using Guava (or just plain Java) without having to loop th

4条回答
  •  無奈伤痛
    2020-12-14 15:41

    Btw. if it is only to be used in some sort of iteration, you could simply create a basic class which implements the Iterable interface, to skip the insertion altogether.

    Something like this:

    import java.util.Iterator;
    
    public class IntegerRange implements Iterable {
        private int start, end;
    
        public IntegerRange(int start, int end) {
            if (start <= end) {
                this.start = start;
                this.end = end;
            } else {
                this.start = end;
                this.end = start;
            }
        }
    
        @Override
        public Iterator iterator() {
            return new IntegerRangeIterator();
        }
    
        private class IntegerRangeIterator implements Iterator {
            private int current = start;
    
            @Override
            public boolean hasNext() {
                return current <= end;
            }
    
            @Override
            public Integer next() {
                return current++;
            }
        }
    }
    

    Which could be used in some way like this:

    Iterable range = new IntegerRange(1, 500);
    
    for (int i : range) {
        // ... do something with the integer
    }
    

提交回复
热议问题