Meaning of two double brackets ([][]) in Java

147 views Asked by At

What is the role of a pair of double brackets ([][]) in Java?

reference code(Leetcode 1351. Count Negative Numbers in a Sorted Matrix):


class Solution {
  public int countNegatives(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    int ans = 0;
    int i = m - 1;
    int j = 0;

    while (i >= 0 && j < n) {
      if (grid[i][j] < 0) {
        ans += n - j;
        --i;
      } else {
        ++j;
      }
    }

    return ans;
  }
}

I tried finding about it on google but was not able to find anything regarding this. Please tell me why we use a double bracket here?

2

There are 2 answers

2
Shovel_Knight On

It is a two-dimensional array, or an array of arrays of int.

0
Ka'Eios On

In Java, double brackets are used to represent 2D-Arrays (an array that contains arrays).

In your code example, this type is used to represent a 2D-Matrix containing integers. First coordinate correspond to rows and second to columns.

Example :

/*
    Consider 3x3 Matrix A
    | 1 2 3 |
    | 4 5 6 |
    | 7 8 9 |
*/

// Represent matrix as a 2D-Array
int[][] matrix = new int[][] {
    {1, 2, 3}, // 1st row
    {4, 5, 6}, // 2nd row
    {7, 8, 9}, // 3rd row
};

// Access coefficient at A(1, 2)
int value = matrix[0][1]; // A(1, 2) is at [0][1] in array because index start at 0.