How to use a java iterator across classes?

I am using this iterator for the board class and now i want to use the stack i return in some other class where i want to iterate over this stact how do i iterate through it using this stack. Thanks in advance

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

Answers


1) Just return Stack<Board>, and not Iterable<Board>. That's if you want the calling code to use the result as a Stack and not just as an Iterable.

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

Alternatively...

2) In the calling code do something like this.

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

Need Your Help

mysql subtract in select

mysql sql

For example, I have the following table: