在搜索有关迭代器的信息时,我只找到了展示如何迭代集合的示例,而不是像我想做的那样返回迭代器。
我正在为考试练习,所以我正在尝试一些编程练习来为自己做准备,而这一个是关于迭代器模式的。
我想实现 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;
}
最佳答案
首先,让你的类实现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");
}};
}
关于java - 返回一个迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20949978/