I have a problem I have been researching for a while on the internet but can not seem to find anything that could help me reach a conclusion.
I have a class Grid. Grid stores a 2D array of type Cell.
public class Grid implements Iterable<Cell>{
private Cell[][] grid;
And I have class Main. I want to be able to iterate over the 2D array grid inside the Grid object, form the Main in such fashion:
public class Main {
Grid grid;
for(Cell c: grid){
//do something
}
}
I can’t simply add:
public Iterator<Cell> iterator() {
retrun grid.iterator();
}
Inside my Grid class because it returns an error.
I do not want the Cell objects to hold the coordinates, I would like the 2D array to represent the coordinate system.
Cell[][] doesn’t implement Iterator. You should create a GridIterator inner class in Grid that implements Iterator and whose next() and hasNext() return whatever you consider to be the “next” Cell, until the grid has been traversed.