I have following code:
public class GameCanvas extends JPanel {
private GridField[][] grid;
private int x, y;
private int fieldSize;
public GameCanvas(int rows, int cols, int fieldSize)
{
this.grid = new GridField[cols][rows];
this.x = cols;
this.y = rows;
this.fieldSize = fieldSize;
}
...
}
Here is the definition of the GridField class:
public class GridField {
private FieldType fieldType;
public GridField() {
fieldType = FieldType.EMPTY;
}
public FieldType getFieldType() {
return fieldType;
}
public void setFieldType(FieldType fieldType) {
this.fieldType = fieldType;
}
}
The problem is, when I try to access the “grid” object, the compiler says it’s null, although I have initialized it in the constructor of the class.
I did a little check:
if(grid[xSize][ySize] == null) {
System.out.println("Grid[x][y] is null");
}
It printed out exactly what I expected – null.
I’m coming to Java from C# background so I might have missed something. I believe, it’s a trivial mistake, but I can’t find it.
Thanks in advance, for any hint.
The above code only initializes the array. You also need to initialize each array elements with
objectsofGridField.Probably something like this: –
This way of initialization is no different in
C#. So, if you initialized arrays like this inC#, then probably you missed something there also. Note the comments from @JonSkeet.