Shortest way to get an Iterator over a range of Integers in Java

后端 未结 7 1978
时光说笑
时光说笑 2020-12-29 22:27

What\'s the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:

/** 
* Returns an Iterator over the in         


        
7条回答
  •  借酒劲吻你
    2020-12-29 22:36

    If you actually want the shortest amount of code, then Bombe's answer is fine. However, it sucks memory for no good reason. If you want to implement it yourself, it would be something like:

    import java.util.*;
    
    public class IntegerRange implements Iterator
    {
        private final int start;
        private final int count;
    
        private int position = -1;
    
        public IntegerRange(int start, int count)
        {
            this.start = start;
            this.count = count;
        }
    
        public boolean hasNext()
        {
            return position+1 < count;
        }
    
        public Integer next()
        {
            if (position+1 >= count)
            {
                throw new NoSuchElementException();
            }
            position++;
            return start + position;
        }
    
        public void remove()
        {
            throw new UnsupportedOperationException();
        }
    }
    

提交回复
热议问题