OutOfBounds when working with objects in an array

时间秒杀一切 提交于 2021-02-17 02:10:59

问题


When I am creating an array of Example objects, I call something like initializeArray(); I use a simple nested for loop to traverse through the array and then assign new objects with values to each index of the array using exampleArr[i][j] = new Example(false, false, false, 0); however, calling this gives me an java.lang.ArrayIndexOutofBoundsException:0 at the line above.

I am assuming that I am instantiating the new object incorrectly, as this also happens in another method which is supposed to display all of the Example objects in the array. However, I will post the nested loop I am using in case there is something that i've done wrong that I can't see.

public void initializeArray(){
    for(int i = 0; i < getRows(); i++){
        for(int j = 0; j < getColumns(); j++){
             tileArr[i][j] = new Tile(false, false, false, 0);
        }
    }
}

//Declaration of rows and columns

    private int rows; 
    private int columns; 
    Tile[][] tileArr = new Tile[rows][columns]; 
public void setRows(int r)
{   
 rows = r; 
} 
 public void setColumns(int c)
 { 
     //various setters and getters for the array 
  columns = c; 
 } 
public int getRows()
{ 

  System.out.print(rows); 
  return rows; 
} 
public int getColumns()
{ 
  System.out.print(columns); 
  return columns; 
} 

Thanks everyone for your help! The problem has been solved.


回答1:


Declare your tileArr at the top but do not initialize.

Tile[][] tileArr; 

Then initialize your array before your for loop in the initializeArray() (This is assuming your rows and columns is set. You can add logic to check this as well).

tileArr = new Tile[getRows()][getColumns()];
tileArr = new Tile[rows][columns]; //Do this instead if you don't want the print statements to be called



回答2:


As @gonzo said you have got to initialize your array to allocate enough memory for all the positions you are going to be using.

Tile[][] tileArr;

public void initializeArray(){
       Tile[][] tileArr = new Tile[getRows()][getColumns()];
       for(int i = 0; i < getRows(); i++){
           for(int j = 0; j < getColumns(); j++){
                tileArr[i][j] = new Tile(false, false, false, 0);
           }
       }
       return titleArr;
}

//...wherever you want it
this.tileArray = this.initializeArray()

But there are cases when you don't know how big this array may be. For those cases you should be using List<Tile> type like LinkedList<Tile> or ArrayList<Tile> so that you don't need to allocate space for every new position to use.



来源:https://stackoverflow.com/questions/33173400/outofbounds-when-working-with-objects-in-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!