如何为 2D 数组/列表创建 Java 迭代器



我最近被问到如何为2D Array创建一个Java迭代器的问题,特别是如何实现:

public class PersonIterator implements Iterator<Person>{
    private List<List<Person>> list;
    public PersonIterator(List<List<Person>> list){
        this.list = list;
    }
    @Override
    public boolean hasNext() {
    }
    @Override
    public Person next() {
    }
}

通过使用索引来跟踪位置,1D 数组非常简单,有关如何为 2D 列表执行此操作的任何想法。

在 1D 情况下,您需要保留一个索引才能知道您离开的位置,对吗?好吧,在 2D 情况下,您需要两个索引:一个用于知道您正在哪个子列表中工作,另一个用于知道您离开该子列表中的哪个元素。

像这样的东西?(注:未经测试)

public class PersonIterator implements Iterator<Person>{
    // This keeps track of the outer set of lists, the lists of lists
    private Iterator<List<Person>> iterator;
    // This tracks the inner set of lists, the lists of persons we're going through
    private Iterator<Person> curIterator;
    public PersonIterator(List<List<Person>> list){
        // Set the outer one
        this.iterator = list.iterator();
        // And set the inner one based on whether or not we can
        if (this.iterator.hasNext()) {
            this.curIterator = iterator.next();
        } else {
            this.curIterator = null;
        }
    }
    @Override
    public boolean hasNext() {
         // If the current iterator is valid then we obviously have another one
         if (curIterator != null && curIterator.hasNext()) {
             return true;
         // Otherwise we need to safely get the iterator for the next list to iterate.
         } else if (iterator.hasNext()) {
             // We load a new iterator here
             curIterator = iterator.next();
             // and retry peeking to see if the new curIterator has any elements to iterate.
             return hasNext();
         // Otherwise we're out of lists.
         } else {
             return false;
         }
    }
    @Override
    public Person next() {
         // Return the current value off the inner iterator if we can
         if (curIterator != null && curIterator.hasNext()) {
             return curIterator.next();
         // Otherwise try to iterate along the next list and retry getting the next one.
         // This won't infinitely loop at the end since next() at the end of the outer
         // iterator should result in an NoSuchElementException.
         } else {
             curIterator = iterator.next();
             return next();
         }
    }
}

最新更新