3

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:

  1. In the for loop it warns that the termination condition is always true. However this wanring only shows for the inner col for loop and not the outer row for loop.
  2. In the assignment of 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]
            }
        }
    }

    ...
}
PLM1995
  • 31
  • 2
  • 1
    Does the problem persist when you restart Android Studio? At first glance, it seems like it's a problem on their end – QBrute Nov 22 '20 at 10:33
  • 4
    This seems to be a bug in Android Studio. Changing the field `grid_size` from `private Integer grid_size;` to `private int grid_size;` removes the warning. – Thomas Kläger Nov 22 '20 at 10:47

1 Answers1

0

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.

amadsalmon
  • 56
  • 8