开发者

Java:multidimensional array problem

In a multidimensional array, is it possible to use the length variable to measure different dimensions other than 开发者_如何学Cthe first?


Yes. Length dimensions vary from row to row. You can do matrix[i].length to get the length of row i. If you know the matrix is square, all the row lengths will equals matrix[0].length anyways, so it doesn't matter.

If you're trying to iterate through all elements:

for(int i = 0; i < matrix.length; i++){
    for(int j < 0; j < matrix[i].length; j++){
        count += matrix[i][j];
    }
}

The same principle can be applied for any number of dimensions. For loops, you need 1 nested loop per dimension. For lengths, each bracketed part is actually a new element, so 3d array ar will yield a 2d array with ar[i], 1d with ar[i][j], and 0d (single element of the array type) with ar[i][j][k]


Yes.

@Test
public void test(){
    long[][][] multi = new long[3][2][1];
    System.out.println(multi.length); //3
    System.out.println(multi[0].length); //2
    System.out.println(multi[0][0].length); //1
}


Sure.

array.length;
array[0].length;
array[1].length;


Well, no, you need array[0].length to get size of second dimension, and array[0][0].length to get length of third. Of course, arrays are not matrices, so array[0].length and array[1].length might be different, depending on the sizes of the sub-arrays you stored at array[0] resp. array[1]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜