在Java中使用一系列整数获取迭代器的最短方法

cre*_*zel 23 java iterator

在Java中使用一系列整数获取迭代器的最短路径是什么?换句话说,实现以下内容:

/** 
* Returns an Iterator over the integers from first to first+count.
*/
Iterator<Integer> iterator(Integer first, Integer count);
Run Code Online (Sandbox Code Playgroud)

就像是

(first..first+count).iterator()
Run Code Online (Sandbox Code Playgroud)

Sai*_*ali 70

此实现没有内存占用.

/**
 * @param begin inclusive
 * @param end exclusive
 * @return list of integers from begin to end
 */
public static List<Integer> range(final int begin, final int end) {
    return new AbstractList<Integer>() {
            @Override
            public Integer get(int index) {
                return begin + index;
            }

            @Override
            public int size() {
                return end - begin;
            }
        };
}
Run Code Online (Sandbox Code Playgroud)

编辑:

在Java 8中,您可以简单地说:

IntStream.range(begin, end).iterator()                // returns PrimitiveIterator.OfInt
Run Code Online (Sandbox Code Playgroud)

或者如果您需要盒装版本:

IntStream.range(begin, end).boxed().iterator()        // returns Iterator<Integer>
Run Code Online (Sandbox Code Playgroud)

  • 虽然列表本身很短,但它返回一个List而不是Iterable / Iterator,后者提供了更多的接口方法。这些未在此处实现,如果在“无法预料”的上下文中使用列表实例,则可能导致意外结果。因此,您可以说此实现违反了List接口协定。同样,在AbstractList中实现迭代器并不像它可能的那么简单,并且使用了比实例更多的实例变量,因此内存占用量很小。因此,我宁愿直接实现Iterable / Iterator。 (2认同)
  • @DanielBimschas 我认为这不是真的。此类确实遵守“不可修改”列表的约定,如 JavaDoc 中为 [`java.util.Collection`](http://docs.oracle.com/javase/7/docs/api/java/util/集合.html)。特别是,如果有人调用“破坏性”方法之一(如“add()”或“remove()”),它会抛出“UnsupportedOperationException”。有关更多详细信息,请参阅 [`java.util.AbstractList`](http://docs.oracle.com/javase/7/docs/api/java/util/AbstractList.html) 的 JavaDoc。 (2认同)

Joa*_*uer 15

未经测试.将其映射到"min,count"是留给读者的练习.

public class IntRangeIterator implements Iterator<Integer> {
  private int nextValue;
  private final int max;
  public IntRangeIterator(int min, int max) {
    if (min > max) {
      throw new IllegalArgumentException("min must be <= max");
    }
    this.nextValue = min;
    this.max = max;
  }

  public boolean hasNext() {
    return nextValue <= max;
  }

  public Integer next() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }
    return Integer.valueOf(nextValue++);
  }

  public void remove() {
    throw new UnsupportedOperationException();
  }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 9

如果你真的想要最短的代码量,那么Bombe的答案就可以了.然而,它没有充分理由吸引记忆.如果你想自己实现它,它将是这样的:

import java.util.*;

public class IntegerRange implements Iterator<Integer>
{
    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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Lee*_*Lee 7

使用番石榴框架的一个例子.请注意,这不会实现集合(尽管您必须阅读ContiguousSet实现以验证它).

import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.DiscreteDomains;

class RangeIterator { 

    public Iterator<Integer> range(int start, int length) {
        assert length > 0;
        Range<Integer> dim_range = Ranges.closedOpen(start, start + length);
        DiscreteDomain<Integer> ints = DiscreteDomains.integers();
        ContiguousSet<Integer> dim = dim_range.asSet(ints);
        return dim.iterator();
    }
}
Run Code Online (Sandbox Code Playgroud)


btp*_*ka3 7

在 java 8 中使用流 API 的示例:

int first = 0;
int count = 10;
Iterator<Integer> it = IntStream.range(first, first + count).iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
Run Code Online (Sandbox Code Playgroud)

如果没有迭代器,它可能是:

int first = 0;
int count = 10;
IntStream.range(first, first + count).forEach(i -> System.out.println(i));
Run Code Online (Sandbox Code Playgroud)


Bom*_*mbe 4

直接实施您的作业:

List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < count; i++) {
    ints.add(first + i);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你认真对待"最短",那是正确的,除了你错过了"return ints.iterator();" ;-) (5认同)
  • 另外,它的内存不足。 (3认同)