如何跨类使用java迭代器?

时间:2014-02-08 18:20:36

标签: java iterator

我正在使用这个迭代器用于板类,现在我想使用堆栈我在其他类中返回我想要迭代这个stact如何使用这个堆栈迭代它。 提前致谢

 public Iterable<Board> neighbors(){
     Stack<Board> boardit=new Stack<Board>();
     int i=0,j=0;
     for(i=0;i<N;i++){
            for(j=0;j<N;j++){
                if(this.board[i][j]==0) break;
                }
            }
     if(this.validate(i-1, j)){
         Board ngh1=new Board(this.board);
         int temp=ngh1.board[i][j];
         ngh1.board[i][j]=ngh1.board[i-1][j];
         ngh1.board[i-1][j]=temp;
         boardit.push(ngh1);
     }
     if(this.validate(i+1, j)){
         Board ngh2=new Board(this.board);
         int temp=ngh2.board[i][j];
         ngh2.board[i][j]=ngh2.board[i+1][j];
         ngh2.board[i+1][j]=temp;
         boardit.push(ngh2);
     }
     if(this.validate(i, j-1)){
         Board ngh3=new Board(this.board);
         int temp=ngh3.board[i][j];
         ngh3.board[i][j]=ngh3.board[i][j-1];
         ngh3.board[i][j-1]=temp;
         boardit.push(ngh3);
     }
     if(this.validate(i, j+1)){
         Board ngh4=new Board(this.board);
         int temp=ngh4.board[i][j];
         ngh4.board[i][j]=ngh4.board[i][j+1];
         ngh4.board[i][j+1]=temp;
         boardit.push(ngh4);
     }

     return boardit;
 }   

1 个答案:

答案 0 :(得分:0)

1)只需返回Stack<Board>,而不是Iterable<Board> 如果您希望调用代码使用结果
,那就是这样 作为Stack,而不仅仅是Iterable

public Stack<Board> neighbors() { ... }

...替代地

2)在调用代码中执行类似的操作。

Iterator<Board> iter = neighbors().iterator();
while (iter.hasNext()){
    Board board = iter.next();
    // do something with board
}