One-dimensional array
1. Initialization
way1:
type[] arrayName = new type[size];
If only specifies the length of the array, then the system will assign initial values to the following rule these array elements:
- Array element type is an integer type value (byte, short, int, and long) basic types, the array elements is 0
- Array element type is a value type of the basic types of floating-point (float, double), the array elements is 0.0
- Array element type is a primitive type of character type (char), the array element is '\ u0000'
- Array element type is Boolean (boolean) basic types, the array element is false
- Array element type is a reference value types (classes, interfaces, and arrays), the array element is null
way2:
type[] arrayName = new type[]{值 1,值 2,值 3,值 4,• • •,值 n};
way3:
type[] arrayName = {值 1,值 2,值 3,...,值 n};
2. iterate
int[] number = {1,2,3,5,8};
for (int i=0;i<number.length;i++) {
System.out.println("第"+(i+1)+"个元素的值是:"+number[i]);
}
for(int val:number) {
System.out.print("元素的值依次是:"+val+"\t");
}
Two-dimensional array
Two-dimensional array is seen as an array of arrays, that is a special two-dimensional array of one-dimensional array, each element is a one-dimensional array
1. Initialization
type[][] arrayName = new type[][]{{值 1,值 2},{值 3,…,值 n}}; // 在定义时初始化
type[][] arrayName = new type[size1][size2]; // 给定空间,在赋值
type[][] arrayName = new type[size][]; // 数组第二维长度为空,可变化
2. traversal
int[][] x = new int[][]{{1,2},{3,4,5}};
for(int i=0; i < x.length; i++){
for (int j =0; j < x[i].length; j++){
System.out.print(x[i][j]+" ");
}
}
way2:
int[][] x = new int[][]{{1,2},{3,4,5}};
for(int[] item:x){
for (int num : item){
System.out.print(num+" ");
}
}