Java-14.3 multi-dimensional array Function
In this section, we will discuss multi-dimensional arrays.
1. Example:
package com.ray.ch14;import java.util.Arrays;public class Test {public static void main(String[] args) {int[][] a = new int[2][2];System.out.println(Arrays.deepToString(a));}}Output:
[0, 0], [0, 0]
The above code is a fixed-length multi-dimensional array.
2. Several forms of creation
First:
package com.ray.ch14;import java.util.Arrays;public class Test {public static void main(String[] args) {int[][] a = new int[2][2];a[0][0] = 1;a[0][1] = 2;a[1][0] = 3;a[1][1] = 4;System.out.println(Arrays.deepToString(a));}}
Second:
package com.ray.ch14;import java.util.Arrays;public class Test {public static void main(String[] args) {int[][] a = { { 1, 2 }, { 3, 4 } };System.out.println(Arrays.deepToString(a));}}
Third:
Package com. ray. ch14; import java. util. arrays; public class Test {public static void main (String [] args) {int [] [] a = new int [2] [2]; // a [0] = {1, 2}; // error. This assignment method can only be used during initialization. // a [0] = 1; // error, a [0] is an array a [0] = new int [] {1, 2}; a [1] = new int [] {3, 4 }; int [] B = {1, 2}; System. out. println (Arrays. deepToString ());}}
Note that the assignment value of a [0] must be new and cannot be used.
However, the following array B can directly execute an array, because this method of assignment can only be used during initialization.
Fourth:
package com.ray.ch14;import java.util.Arrays;public class Test {public static void main(String[] args) {int[][] a = new int[][] { { 1, 2 }, { 3, 4 } };System.out.println(Arrays.deepToString(a));}}
3. Notes
Example:
package com.ray.ch14;import java.util.Arrays;public class Test {public static void main(String[] args) {// int[][][] a1 = new int[][][2];//error// int[][][] a2 = new int[][2][];//error// int[][][] a3 = new int[2][][2];//error// int[][][] a4 = new int[][][];//errorint[][][] a = new int[2][][];System.out.println(Arrays.deepToString(a));}}
Observe the code above and draw the following conclusion:
1. the number that controls the length can be blank.
2. The dimension before the dimension with length control must also have length control. Here it is a detour. Please observe a1, a2, a3, a4
3. At least one dimension with Length Control
4. initialize dimensions without Length Control
package com.ray.ch14;import java.util.Arrays;public class Test {public static void main(String[] args) {// int[][][] a1 = new int[][][2];//error// int[][][] a2 = new int[][2][];//error// int[][][] a3 = new int[2][][2];//errorint[][][] a = new int[2][][];a[0] = new int[][] { { 1, 2 }, { 3, 4 } };a[1] = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 } };System.out.println(Arrays.deepToString(a));}}
Output:
[[1, 2], [3, 4], [1, 2], [3, 4], [5, 6]
5. Use Cases
Multi-dimensional arrays are generally used for matrix display and calculation.
Summary: This chapter describes several basic aspects of multi-dimensional arrays.
This chapter is here. Thank you.