Test length of multiple dimensions of an array in Java
I'm a Java noob. I don't know very much about the language (at least开发者_如何学JAVA, not enough to do complex things) right now, but I'm getting there!
I know you can test the length of a single-dimensioned array by doing arr.length
, but is it possible to test other dimensions (in a multidimensional array)?
Yes, it is. Obviously, to test the first dimension you would just do arr.length
. Subsequent dimensions are tested by using length
with the [0]
element of that particular dimension. For example, consider this array:
int[][][][] arr = new int[10][11][12][13];
To test the...
first dimension:
arr.length;
second dimension:
arr[0].length;
third dimension:
arr.[0][0].length;
fourth dimension:
arr.[0][0][0].length;
A multidimensional array is just an array of arrays, and each array in the array can have different lengths. I.e.:
int arr[][] = new int[2][];
arr[0] = new int[5];
arr[1] = new int[10];
System.out.println(arr.length);
System.out.println(arr[0].length);
System.out.println(arr[1].length);
Now you have a two-dimensional array. The first dimension (outer) can be referred to as arr
and is of size 2. The inner arrays can be referred to as arr[0] and arr[1] and have lengths 5 and 10, respectively. Since each of these refers to a normal Java array, you can use all the normal ways of accessing an arry on them. Further, since we create multidimensional arrays by putting arrays in arrays, you can have as many dimensions as you want, and you access each further level down by indexing into the one above: arr[2][1][5][11][3][0][123][5][42][9][7]....length
Given, say, a 2D array, you can access the length of the i
th inner array with arr[i].length
.
If you haven't already seen it, check out Arrays (The Java™ Tutorials).
You can test the other dimensions of the other dimensions by directly referrencing the dimension you are wanting to test.
For example, if you have a 2 dimensional array with 3 items in the primary dimension then you can identify the length of each of them by using arr[0].length, arr[1].length, and arr[2].length.
the code below just sets up an array, and then verifies that the lengths are what we expect them to be.
public void testLength(){
//setup the array you are wanting to test
int[][] foo = new int[2][5];
// this just makes sure that we do get 2 dimensions within the primary
Assert.assertEquals(2,foo.length);
Assert.assertEquals(5,foo[0].length);
// change the array stored within foo[0]
foo[0]= new int[8];
Assert.assertEquals(8,foo[0].length);
}
精彩评论