返回一个迭代器

5

当我搜索关于迭代器的信息时,我只找到了一些展示如何遍历集合而不是返回迭代器的例子,而我想要的是后者。

我正在练习考试,所以我正在尝试一些编程练习来准备自己,其中一个是关于迭代器模式的。我想要实现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+"]";
    }
}

然而,我发现我需要创建一个迭代器来返回结果,因此,到目前为止,这是我的尝试。

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;
}

1
当前位置 currentPosition = 位置集合.next() - Mr. Polywhirl
这样做不仅仅只会查看下一个位置吗?我需要以某种方式保存所有的位置,以便它们可以通过迭代器返回。迭代器是否保存它遇到的所有位置? - user1960836
1
迭代器被用来移除/检查集合中的元素,而不是“跟踪项目”。 - Mr. Polywhirl
是的,我也是这么想的。那么我该如何使用currentPosition(您建议的代码)和knightPosIter呢?到目前为止,我编写的代码是否正确? - user1960836
1
检查当前棋子位置是否在棋盘范围内,因为该位置类包含行/列信息,所以应该能够确定其位置是否合法。 - Mr. Polywhirl
1个回答

9
首先,让您的类实现 Iterable 接口。
public class Position implements Iterable<Position>

请不要提供静态方法,按照以下方式编写public Iterator<Positions> iterator();方法。

由于您实际上需要以某种方式计算可达位置的集合,因此您需要一个用于保存它的结构。任何这样的结构通常都是可迭代的,并且将具有迭代器方法。因此,懒惰实现可能如下:

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

如果您有其他计算和存储位置的结构,而这些结构不可迭代(不建议使用),则可以按照以下方式从头开始实现一个迭代器(假设为位置数组):

@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");
        }};
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接