一、对二维数组的理解
1.二维数组其实是一个特殊的一维数组,特殊在这个一维数组当中的每一个元素是一个一维数组
二维数组静态初始化
int[][] array = {{},{},{},};
package array;
public class ArrayTest09 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] a = {
{100, 200, 300},
{30, 20, 40, 50, 60},
{6, 7, 9, 1},
{0}
};
}
}
二维数组的动态初始化
public class ArrayTest12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] array = new int[3][4];
}
}
二、二维数组的length属性
package array;
public class ArrayTest09 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] a = {
{100, 200, 300},
{30, 20, 40, 50, 60},
{6, 7, 9, 1},
{0}
};
System.out.println(a.length);
System.out.println(a[0].length);
}
}
4
3
三、二维数组的元素访问
关于二维数组中元素的读和改
a[二维数组中的一维数组坐标**][一维数组中的元素下标]**
package array;
public class ArrayTest09 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] a = {
{34, 4, 65},
{100, 200, 3900, 111},
{0}
};
//请取出以上二位数中的第一个一维数组
int[] a0 = a[0];//a0只是一个一维数组的变量名
System.out.println(a0[0]);//一维数组中的第一个元素
System.out.println(a[0][0]);
//改
a[2][0] = 11111;
System.out.println(a[2][0]);
}
}
四、遍历二维数组
package array;
public class ArrayTest11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[][] array = {
{"java", "oracle", "c++", "python", "c#"},
{"张三","李四","王五"},
{"lucy", "jack", "rose"}
};
//遍历二维数组
for(int i = 0; i<array.length; i++) {
for(int j = 0; j<array[i].length; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
五、方法的参数是一个二维数组
public class ArrayTest12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//int[][] array = new int[3][4];
int[][] a = {
{1,2,3,4},
{4,5,6,76},
{1,23,4}
};
printArray(a);
}
public static void printArray(int[][] array) {
for(int i = 0; i<array.length; i++) {
for(int j = 0; j<array[i].length; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
//这样也可以,省掉变量a
printArray(new int[][] {{1,2,3,4},{4,5,6,76},{1,23,4}});