-2

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 5
    It is an array of which the elements are arrays of integers. – Jesper Aug 14 '23 at 09:40
  • 2
    "I tried finding about it on google ..." - How about reading the Oracle Java tutorial? https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – Stephen C Aug 14 '23 at 10:00
  • The clue is in the problem name: .... Matrix ... – Arfur Narf Aug 14 '23 at 12:20
  • 1
    @Stephen_C For each question you may ask on SO, there's a book or a web site you could read instead. This could go with all the questions you asked on SO too. When you are a complete beginner in Java, SO is helpful for you. – Marc Le Bihan Aug 14 '23 at 12:42

2 Answers2

2

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

  • 3
    Technically, two-dimensional arrays don't exist in Java. Those imply a grid, where each nested array has the same length. In an `int[][]`, each nested array can have a different length. The term "array of arrays of `int`" is spot-on though. – Rob Spoor Aug 14 '23 at 09:53
  • 1
    @RobSpoor Which are colloquially called two-dimensional arrays. – Mark Rotteveel Aug 14 '23 at 10:07
2

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.
Ka'Eios
  • 61
  • 6