Search code examples
javaarrayshexagonal-tiles

How do I create an iterator from a regular array in Java?


public class TileGrid implements Iterable<Tile> {
    private wheelSize = [a positive integer];
    private Tile[][] grid = new Tile[wheelSize * 2 + 1][wheelSize * 2 + 1]

    @Override
    public Iterator<Tile> iterator() {
        return ????????;
    }
}

I've made a TileGrid class to keep track of a hex-grid for me. It stores Tile-objects in a two dimensional array called grid. Now I want to make the TileGrid class Iterable so that I can easily loop through all Tile-objects. The problem is that there is some positions in the array that is naturally not used (due to the shape of the hex-grid) and thus contains the value null.

My question is this: How do I create an iterator that iterates through all positions in grid except the ones that is null?

I do not want to use some kind of ArrayList since I'm using the array indexes to mark the position of the Tiles.


Solution

  • @HopefullyHelpful

    My version:

    public Iterator<Tile> iterator() {
        return new TileIterator(grid);
    }
    

    .

    class TileIterator implements Iterator<Tile> {
    
        int x = 0, y = -1;
        int newX, newY;
        Tile[][] grid;
    
        TileIterator(Tile[][] grid) {
            this.grid = grid;
            updateNewIndex();
        }
    
        public boolean hasNext() {
            if (newX == -1) {
                return false;
            }
            return true;
        }
    
        public Tile next() {
            x = newX;
            y = newY;
            updateNewIndex();
            if (x == -1) {
                throw new NoSuchElementException("no more elements left");
            }
            return grid[x][y];
        }
    
        private void updateNewIndex() {
            newX = x;
            newY = y;
            do {
                newY++;
                if (newY == grid[newX].length) {
                    newY = 0;
                    newX = newX + 1;
                    if (newX == grid.length) {
                        newX = newY = -1;
                    }
                }
            } while (newX != -1 && grid[newX][newY] == null);
        }
    }
    

    Thanks again for your answer as it helped me make this.