JavaSE010_数组之二维数组的实质和遍历

来源:互联网 发布:淘宝怎样取消退款申请 编辑:程序博客网 时间:2024/04/29 10:39

1、二维数组的实质是一维数组

/* * type [][] arrName * Java语言采用上面的语法格式来定义二维数组,但它的实质还是一维数组, * 只是其数组元素也是引用,数组元素里保存的引用指向一维数组。 *  * 同样可以把这个二维数组当成以为数组来初始化:arrName = new type[length][] * 上面的语法相当于初始化了一个一维数组,这个一维数组的长度时length * 因为这个一维数组的数组元素时引用类型(数组类型)的,所以系统为每个数组元素都分配初始值:null */public class TestTwoDimension {public static void main(String[] args) {// 定义一个二维数组int[][] a;// 把a当成一维数组进行初始化,初始化a是一个长度为3的数组// a数组的数组元素又是引用类型a = new int[3][];// 把a这个二维数组当成一维数组处理,遍历a数组的每个数组元素for (int i = 0; i < a.length; i++) {System.out.println(a[i]);//每个数组元素都是null,所以输出结果都是null}// 初始化a数组的第一个元素a[0] = new int[2];// 访问a数组的第一个元素所指数组的第二个元素a[0][1] = 6;// a数组的第一个元素是一个一维数组,遍历这个一维数组for (int i = 0; i < a[0].length; i++) {System.out.println(a[0][i]);}// 同时初始化二维数组的2个维数int[][] b = new int[3][4];// 使用静态初始化的语法来初始化一个二维数组String[][] str1 = new String[][] { new String[3], new String[] { "hello" } };// 使用简化的静态初始化语法来初始化二维数组String[][] str2 = { new String[3], new String[] { "hello" } };}}

输出结果为:

null
null
0
6

2、遍历二维数组

/* * 遍历二维数组方式一 */public class TestTwoDimension {public static void main(String[] args) {int arr[][] = new int[][] { { 1 }, { 1, 2 }, { 1, 2, 3 } };for (int i = 0; i < arr.length; i++) {int[] arr2 = arr[i];for (int c = 0; c < arr2.length; c++) {System.out.print(arr2[c]);}System.out.println();}}}
输出结果为:

1
12
123

/* * 遍历二维数组方式二 */public class TestTwoDimension {public static void main(String[] args) {int arr[][] = new int[][] { { 1 }, { 1, 2 }, { 1, 2, 3 } };for (int i = 0; i < arr.length; i++) {for (int j = 0; j < arr[i].length; j++) {System.out.print(arr[i][j]);}System.out.println();}}}

输出结果为:

1
12
123

/* * 遍历二维数组方式三 */public class TestTwoDimension {public static void main(String[] args) {int arr[][] = new int[][] { { 1 }, { 1, 2 }, { 1, 2, 3 } };for (int i = 0; i < arr.length; i++) {for (int j = 0; j < arr[i].length; j++) {System.out.println(arr[i][j]);}System.out.println();}}}
输出结果为:

1

1
2

1
2
3

0 0
原创粉丝点击