Java 返回一个迭代器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20949978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:30:33  来源:igfitidea点击:

Return an iterator

javadesign-patternsiterator

提问by user1960836

Searching for info about the iterator, I found only examples that showed how to iterate over a collection, and not returning the Iterator, like I want to do.

在搜索有关迭代器的信息时,我只找到了展示如何迭代集合的示例,而不是像我想做的那样返回迭代器。

I am practicing for the exam, so I'm trying out some programming excercises to prepare myself, and this one is about the iterator pattern. I want to implement the getKnightPositionIterator, . You can see the code below. This code is not mine, I found this.

我正在为考试练习,所以我正在尝试一些编程练习来为自己做准备,这个练习是关于迭代器模式的。我想实现getKnightPositionIterator, . 你可以看到下面的代码。这段代码不是我的,我发现了这个。

package iterator;        
import java.util.*;

public class Position {

    /** return an iterator that will return all positions
     * that a knight may reach from a given starting position.
     */
    public static Iterator<Position> getKnightPositionIterator(Position p) {    


        return null;
    }


    /** create a position. 
     * @param r the row
     * @param c the column
     */
    public Position(int r, int c) { 
        this.r = r; this.c = c; 
    }

    protected int r;
    protected int c;

    /** get the row represented by this position.
     * @return the row.
     */
    public int getRow() { return r; }

    /** get the column represented by this position.
     * @return the column.
     */
    public int getColumn() { return c; }

    public boolean equals(Object o) {
        if (o.getClass() != Position.class) { return false; }
        Position other = (Position) o;
        return r==other.r && c==other.c;
    }

    public int hashCode() {
        // works ok for positions up to columns == 479
        return 479*r+c;
    }

    public String toString() {
        return "["+r+","+c+"]";
    }
}

How ever, I figure that I have to create an Iterator to return, so, so far, this is my attemp.

但是,我认为我必须创建一个 Iterator 才能返回,因此,到目前为止,这是我的尝试。

public static Iterator<Position> getKnightPositionIterator(Position p) {    
    Iterator<Position> knightPosIter = Position.getKnightPositionIterator(p);

    for(Iterator<Position> positions = knightPosIter; positions.hasNext(); ) {
        //What should I write here?
    }

    return knightPosIter;
}

采纳答案by Oleg Sklyar

First, make your class implement Iterableinterface

首先,让你的类实现Iterable接口

public class Position implements Iterable<Position>

and write the public Iterator<Positions> iterator();method as outlined below instead of providing a static method in your example.

public Iterator<Positions> iterator();按照下面概述的方式编写方法,而不是在您的示例中提供静态方法。

As you actually need to compute a collection of reachable positions in one way or another, you will need a structure to hold it. Any such structure will normally be iterable and, thus, will have an iterator method. So a lazy implementation could look like this:

由于您实际上需要以一种或另一种方式计算一组可到达的位置,因此您将需要一个结构来保存它。任何这样的结构通常都是可迭代的,因此会有一个迭代器方法。所以一个懒惰的实现可能是这样的:

@Override
public Iterator<Position> iterator()
{
    // make sure this returns e.g. Collections.unmodifiableList
    Collection<Position> positions = computeReachablePositions(); 
    return positions.iterator();
 }

In case you have some other structure to compute and store your positions that is not iterable (not advisable), implement an iterator from scratch as follows (an array of positions assumed):

如果您有一些其他结构来计算和存储不可迭代(不可取)的位置,请按如下方式从头开始实现迭代器(假设位置数组):

@Override
public Iterator<Position> iterator()
{
    // must be final to be accessible from the iterator below
    final Position[] positions = computeReachablePositions();

    return new Iterator<Position>() {

        int index = 0;

        @Override
        public boolean hasNext()
        {
            return index < positions.length;
        }

        @Override
        public Position next()
        {
            if (hasNext())
            {
                Position value = positions[index];
                index++;
                return value;
            }
            throw new NoSuchElementException("No more positions available");
        }

        @Override
        public void remove()
        {
            throw new UnsupportedOperationException("Removals are not supported");
        }};
}