# Number of Columns

Harish Venkatachalam

Greenhorn

Posts: 3

posted 12 years ago

- 0

What is the function or method which gives me the no of columns(elements) an array contains? For e.g if I have an array called

TestArray[] testArray

I think testArray.length or testArray.length will give me the no of rows the array contains. But I want the nr of columns, is there a method of function I can use? Thanks.

TestArray[] testArray

I think testArray.length or testArray.length will give me the no of rows the array contains. But I want the nr of columns, is there a method of function I can use? Thanks.

posted 12 years ago

- 0

A Java array is always a linear, one-dimensional thing. The .length member tells you how long it is.

Now, you can simulate multi-dimensional arrays by having an array that contains other arrays,and the Java language by using special notation for arrays of arrays -- i.e., an "int[][]" is an array of arrays of integers. The interesting thing about this arrangement is that every one of the nested arrays can have a different length -- i.e.,

If you want to know the length of one particular "column" of "matrix", you can ask for it specificially: matrix[0].length is 3, matrix[1].length is 2, etc. But it doesn't make any sense to ask matrix itself for the size of its second dimension overall, you see?

If you know that you created an array "squareMatrix" such that every sub-array is the same length, then squareMatrix[0].length will give you that length; there's no other way to do this.

Now, you can simulate multi-dimensional arrays by having an array that contains other arrays,and the Java language by using special notation for arrays of arrays -- i.e., an "int[][]" is an array of arrays of integers. The interesting thing about this arrangement is that every one of the nested arrays can have a different length -- i.e.,

If you want to know the length of one particular "column" of "matrix", you can ask for it specificially: matrix[0].length is 3, matrix[1].length is 2, etc. But it doesn't make any sense to ask matrix itself for the size of its second dimension overall, you see?

If you know that you created an array "squareMatrix" such that every sub-array is the same length, then squareMatrix[0].length will give you that length; there's no other way to do this.