如何为2D数组/列表创建Java Iterator

时间:2014-11-26 20:58:51

标签: java iterator

最近我被问到如何为2D数组创建Java Iterator的问题,具体如何实现:

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() {

    }
}

通过使用索引跟踪位置,以及如何为2D列表执行操作,1D数组非常简单。

2 个答案:

答案 0 :(得分:0)

在1D案例中,你需要保留一个索引来知道你离开的地方,对吧? 那么,在2D情况下,你需要两个索引:一个知道你在哪个子列表工作,另一个知道你离开的子列表中的哪个元素。

答案 1 :(得分:0)

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

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();
         }
    }
}
相关问题