当我搜索关于迭代器的信息时,我只找到了一些展示如何遍历集合而不是返回迭代器的例子,而我想要的是后者。
我正在练习考试,所以我正在尝试一些编程练习来准备自己,其中一个是关于迭代器模式的。我想要实现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;
}
当前位置 currentPosition = 位置集合.next()
。 - Mr. Polywhirl