如何跨类使用java迭代器?

如何跨类使用java迭代器?,java,iterator,Java,Iterator,我在board类中使用这个迭代器,现在我想使用我在其他类中返回的堆栈,在这个类中我想迭代这个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++){

我在board类中使用这个迭代器,现在我想使用我在其他类中返回的堆栈,在这个类中我想迭代这个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只需返回堆栈,而不是Iterable。 如果您希望调用代码使用该结果,则需要这样做 作为一个堆栈,而不仅仅是一个Iterable

公共堆栈邻居{…}

或者

2在调用代码中,执行以下操作

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

请澄清。您打算如何调用此代码?就像我想在每个板上运行某些操作后运行此堆栈并插入到优先级队列中一样,但是API规范要求我使用Iterable,那么我该怎么做呢?调用代码不应该尝试将其用作堆栈,而是作为Iterable使用。你的问题和要求之间存在矛盾。我不明白你能不能请elobarateYes,见上文第2项。