Java Learning Path Record
This article is based on an array of basic summary of three content:
A one-dimensional array of type string with the definition and initialization of a two-dimensional array. How two-dimensional arrays traverse access. Take String as an example, other types of array definitions, initialization, and access are similar.
the definition and initialization of one-dimensional arrays
public class Arrayinit {public
static void Main (string[] args) {
//statically initialized array: Method one
String cats[] = new string[] { "
Tom", "Sam", "Mimi"
};
Static initialization array: Method two
String dogs[] = {"Jimmy", "Gougou", "Doggy"};
Dynamic initialization Data
String books[] = new string[2];
Books[0] = "thinking in Java";
BOOKS[1] = "effective Java";
System.out.println (cats.length);
System.out.println (dogs.length);
System.out.println (books.length);
}
definition and initialization of two-dimensional arrays and three methods of traversal
In Java, a two-dimensional array is the equivalent of an array of one-dimensional arrays.
See Code directly
Import Java.util.Arrays; public class Demo {public static void main (string[] args) {//method 1; Define and initialize arr int[][] Arr=new int[3][4
];
Arr[0][1]=1;
arr[0][2]=2;
arr[1][2]=3;
arr[1][1]=4;
arr[2][3]=8; Traversal arr for (int i=0;i<arr.length;i++) {for (int j=0;j<arr[i].length;j++) {System.ou
T.println ("arr[" + i + "] [" + j + "]=" + arr[i][j]);
} System.out.println ("====================================");
Method Two: Define and initialize str; string[][] str1= new string[][]{{"A", "B", "C",},{"D", "E", "F",},{"G", "H", "I"}};
Method Three: Define and initialize str; string[][] str={{"A", "B", "C",},{"D", "E", "F",},{"G", "H", "I"}};
Traversal str Method 1: Use two-tier for loop.
for (int i=0;i<str.length;i++) {//i controls a one-dimensional array. for (int j=0;j<str[i].length;j++) {//j traverses the elements of each one-dimensional array System.out.println ("str[" + i + "] [" + j + "]=" + str[i][j
]);
} //Traversal str Method 2: Use a foreach loop. For each cannot automatically handle every element of a two-dimensional array, it is handled in rows. is processed by a one-dimensional array.
So to access two-dimensional arrays//You must use two nested loops.
for (string [] row:str) {for (string s:row) {System.out.println (s); }//Traversal str Method 3: To quickly print a list of data elements for a two-dimensional array, you can call SYSTEM.OUT.PRINTLN (arrays.deeptostring) directly (s
TR)); }
}
Enter the results as follows
Arr[0][0]=0
arr[0][1]=1
arr[0][2]=2
arr[0][3]=0
arr[1][0]=0
arr[1][1]=4
arr[1][3]=0
arr[2][0]=0
arr[2][1]=0
arr[2][2]=0
arr[2][3]=8
======================= =================
str[0][0]=a
str[0][1]=b
str[0][2]=c
str[1][0]=d
str[1][1]=e Str[1][2]=f
str[2][0]=g
str[2][1]=h
str[2][2]=i
a
b
c
d
e
f
G
H
i
[[A, B, C], [D, E, F], [G, H, I]]