In Java, a two-dimensional array is the same as a one-dimensional array, but differs from a two-dimensional array in C:
1. In Java, a two-dimensional array can be considered an array as an array of elements, for example:
int a[][] = {{1,2},{3,4,5,6},{7,8,9}};
Easy to know: a[0] means that a one-dimensional array {1,2};a[1] represents a one-dimensional array {3,4,5,6};a[2] for a single-dimensional array {7,8,9}.
2. The Declaration and initialization of multidimensional arrays in Java should be in the order from high to low (left to right), for example:
int a[][] = new int[3][];
A[0] = new INT[2];
A[1] = new INT[4];
A[2] = new INT[3];
int t1[][] = new INT[][4]; Illegal
3. Initialization of two-D arrays
3.1 Static initialization
int aa[][] = {{1,2},{2,3},{3,4,5}};
int bb[3][2] = {{1,2},{2,3},{4,5}}; Illegal
3.2 Dynamic Initialization
int a[][] = new INT[3][5];
int b[][] = new int[3][];
B[0] = new INT[2];
B[1] = new INT[3];
B[2] = new INT[5];
4. Demo Analysis
Demo_1
public class test{public static void Main (string[] args) { int a[][] = {{1,2},{3,4,5,6},{7,8,9}}; for (int i=0;i<a.length;i++) {for (int j=0;j<a[i].length;j++) { System.out.print ("a[" +i+ "[" +j+ "]=" +a I [j]+ " "); } System.out.println ();}}}
Operation Result:
a[0][0]= 1 a[0][1]= 2
A[1][0]= 3 a[1][1]= 4 a[1][2]= 5 a[1][3]= 6
a[2][0]= 7 a[2][1]= 8 a[2][2]= 9
Demo_2
public class Test{public static void Main (string[] args) {String s[][] = new String[3][];s[0] = new String[2];s[1] = new St RING[3];S[2] = new string[2];for (int i=0;i<s.length;i++) {for (int j=0;j<s[i].length;j++) {S[i][j] = new String (" My location is: "+" ["+i+"] "+" ["+j+"] ");}} for (int i=0;i<s.length;i++) {for (int j=0;j<s[i].length;j++) {System.out.print (s[i][j]+ "");} System.out.println ();}}}
Operation Result:
My position is: [0][0] My position is: [0][1]
My position is: [1][0] My position is: [1][1] My position is: [note]
My position is: [2][0] My position is: [2][1]
5. Copy of the array: using the static method of Java.lang.System.arraycopy, the array can be copied, and no new objects will be created;
The invocation format is as follows:
System.arraycopy (SRC, Srcpos, dest, Destpos, length)
Indexoutofboundsexception exception is thrown if the number of source data exceeds the target array bounds
Class Test {public static void main (string[] args) {String s[] = {"Songbo", "Yanjixiong", "Wanghaowei", "Shangxiaohui"}; String sbak[] = new STRING[6]; System.arraycopy (S, 0, Sbak, 0, 4); for (int i=0;i<sbak.length;i++) {System.out.println (sbak[i]+ " ");}}
Operation Result:
Songbo
Yanjixiong
Wanghaowei
Shangxiaohui
Null
Null
Java Two-dimensional array