I'm trying to develop my first android app using android studio, and am getting a couple of warnings I can't seem to get rid of in an inner class constructor:
col for loop and not the outer row for loop.grid[row][col], it warns that the array index [row] is out of bounds, but not that the index [col] is.I don't understand why the warnings are appearing at all, given the code seems to run as intended, but also why the warnings only appear for one for loop and one index, when surely any problem would also apply to the other? Any help is much appreciated!
private class MyInnerClass {
private final Character UNKNOWN = '.';
// State data
private String id;
private Integer grid_size;
private final Character[][] grid;
// Constructor
public MyInnerClass(String id, Integer grid_size) {
// Check the grid size is in the permitted range
String[] permitted_grid_sizes = getResources()
.getStringArray(R.array.permitted_grid_sizes);
int min_permitted_grid_size = Integer
.parseInt(permitted_grid_sizes[0]);
int max_permitted_grid_size = Integer
.parseInt(permitted_grid_sizes[permitted_grid_sizes.length - 1]);
if ((grid_size < min_permitted_grid_size) || (grid_size > max_permitted_grid_size)) {
throw new IllegalArgumentException(
"specified grid size (" + grid_size + ") out of range");
}
// Initialise metadata
this.id = id;
this.grid_size = grid_size;
// Initialise a blank grid
this.grid = new Character[this.grid_size][this.grid_size];
for (int row = 0; row < this.grid_size; row++) {
for (int col = 0; col < this.grid_size; col++) { // Gives warning "Condition 'col < this.grid_size' is always 'true'"
this.grid[row][col] = UNKNOWN; // Gives warning "Array index is out of bounds" on [row]
}
}
}
...
}
I believe the issue is related to variable typing.
The field grid_size is of class Integer and you are comparing it with row and col which are of primitive type 'int'.
grid_size == row compares a reference to a value.
What's probably happening is that your IDE is detecting this problem but giving you inaccurate warnings.
If you change grid_size to primitive type int, the warnings should go away.