Definition of one-dimensional array int[] arr1 = new int[3];//arr1 = {}; error int[] arr2 = new int[]{1,2,3};//int[] arr2 = new int[3]{1,2,3}; error int Arr3[] = {4,5,6};//The definition of a two-dimensional array//two-dimensional array with a consistent array of one-dimensional arrays int[][] Arr4 = new int[2][3];//A one-dimensional array in a two-dimensional array with inconsistent length array 2 One- dimensional array one length 21 lengths 3int [] Arr5 = new Int[2][];arr5[0] = new Int[2];arr5[1] = new int[3];//traverse for (int[] i:arr5) {for (int k:i) {System.out.print ln (k); if (k = = i.length-3) System.out.print ("good");//There's an interesting question in it}}
Ps
- Array declaration, int[] arr and int arr[] are all OK
int["arr2 = new Int[]{1,2,3};int Arr3[] = {4,5,6};
- when using the foreach traversal, the result of the above output code is
000good0good0good
The two-dimensional array arr5 is not initialized, so the default value is 0, why my code is written in k = = I.length-3 will output after three good, the default value of K can be 0, so the reason is that the length of this I will change, the reason for the change in length is that this is two int[] I Array, the first array length is 2 the second length is 3
//If I change the code to K = = i.length-2//then the output is 0good0good000// The reason is that when the first array is encountered, the length is 2, so the statement executes, when the second one-dimensional array is encountered, because the length is 3, so the//i.length-1 is 1, so it is not equal to K (default is 0)
In summary, meaning that, The second foreach is actually a continuous traversal of all the one-dimensional arrays.
- Also in a two-dimensional array, directly using Arr5.length returns the number of one-dimensional arrays in a two-dimensional array, Arr5[0].length returns the length of the one-dimensional array
Java Array definition learn some essays