ArrayIndexOutOfBoundsException when initializing a 2dimensional array of objectts

前端 未结 4 1739
盖世英雄少女心
盖世英雄少女心 2021-01-29 02:40

I have a very simple question but i can\'t figure out why I\'m having this exception. I\'m trying to create a 2-dimensional Array of objects for a sudoku puzzle, but when I\'m i

相关标签:
4条回答
  • 2021-01-29 03:17

    The problem is that the default value for an int is 0.

    So when you create your Sudoku object, grid = new Cell[lines][lines]; is equivalent to grid = new Cell[0][0];

    Either change your makeGrid method or provide a size in your constructor.

    public void makeGrid(int size) {
         this.lines = size;
         grid = new Cell[size][size];
         for(int i=0;i<size;i++){
              for(int j=0;j<size;j++){
                  grid[i][j] = new Cell();
              }
         }
     }
    
    0 讨论(0)
  • 2021-01-29 03:19

    You should move your grid initialization into the make grid method since in the constructor the member lines is still not initialized with your desired value (default value of int is 0 so you get an empty array and you try to access it afterwards with bigger unallocated bounds)

    public void makeGrid(int size) {
          this.lines = size; // If you do not need lines anywhere else then it is redundant
          grid = new Cell[size][size];
          for(int i=0;i<size;i++)
                for(int j=0;j<size;j++)    {
                  grid[i][j] = new Cell();
                }
          }
    
    0 讨论(0)
  • 2021-01-29 03:30

    grid = new Cell[lines][lines]; creates an array of size [0][0] because lines is still 0 when that statement is run.

    Whavetever changes you make to lines later on won't affect the array size, which will remain [0][0]...

    Simpler example:

    int size = 0;
    Object[] array = new Object[size];
    size = 1;
    System.out.println(array.length); //prints 0, not 1
    
    0 讨论(0)
  • 2021-01-29 03:31

    Initialize lines before creation of array. Now you creating array with 0x0 dimensions, because lines is 0 be default.

    lines = 10; // Add this line   
    grid = new Cell[lines][lines];
    
    0 讨论(0)
提交回复
热议问题