Java: Initializing a multidimensional array

Java has no built-in support for “true” multidimensional arrays, only arrays of arrays. See this article for the difference: Matrices and Multidimensional Arrays

You can declare and allocate a multidimensional array, as follows (note that it's automatically initialized with zeroes):

// A 2×3×4 array, initialized with zeroes:
int[][][] multidim = new int[2][3][4];

You can also declare and initialize as follows:

// A 2×3×4 multidimensional array:
int[][][] multidim = {
    {
        {  1,  2,  3,  4},
        {  5,  6,  7,  8},
        {  9, 10, 11, 12}
    },
    {
        { 13, 14, 15, 16},
        { 17, 18, 19, 20},
        { 21, 22, 23, 24}
    }
};

Here's how to first allocate the array, then initialize with loops:

// A 2×3×4 multidimensional array:
int[][][] multidim = new int[2][3][4];

// Fill it with the value 10
for (int i = 0; i < multidim.length; i++) {
    for (int j = 0; j < multidim[i].length; j++) {
        for (int k = 0; k < multidim[i][j].length; k++) {
            multidim[i][j][k] = 10;
        }
    }
}

See also

Comments

Be the first to comment!