针对上一讲内容的引用类型数组,这里再做一次剖析,回顾上一个程序:
Person[] p = new Person[3]; p[0] = new Person(10); p[1] = new Person(20); p[2] = new Person(30);
图33-1
举一个例子,利用数组输出数组奇数下标的数组内容为zhangsan,偶数下标的数组内容为lisi。
public class ArrayTest3{ public static void main(String[] args) { Student[] s = new Student[100]; for(int i = 0; i < s.length; i++){ s[i] = new Student(); if(i % 2 == 0){ s[i].name = "zhangsan"; } else{ s[i].name = "lisi"; } System.out.println(s[i].name); } } } class Student{ String name; }【说明】:其中判断数组下标代码段可以用三元运算来实现更加简单。
/* if(i % 2 == 0){ s[i].name = "zhangsan"; } else{ s[i].name = "lisi"; }*/ s[i].name = i % 2 == 0 ? "zhangsan" : "lisi";
1. 二维数组。二维数组是一种平面的二维结构,本质上是数组的数组。二维数组的定义方 式:
type[ ][ ] a = new type[2][3];
之前定义的是一维数组,体现的是线性结构,现在定义的是二维数组,体现的是平面的结构
public class ArrayTest4{ public static void main(String[] args) { int[][] a = new int[2][3]; System.out.println(a instanceof Object); System.out.println(a[0] instanceof int[]); } }
编译执行结果:
D:\src>java ArrayTest4
true
true
【说明】:System.out.println(a instanceof Object);验证数组是一个对象,输出为true。System.out.println(a[0] instanceof int[ ]);验证a[ 0]是一个一维的数组,表示数组的行,输出为真。
i[0][0] = 1; 给数组第一行第一列赋值为1;
继续修改程序,并给数组赋值,按以下图所示:
图33-2
public class ArrayTest4{ public static void main(String[] args) { int[][] a = new int[2][3]; int m = 0; for(int i = 0; i < 2; i++){ for(int j = 0; j < 3; j++){ m++; a[i][j] = m * 2; System.out.println(a[i][j]); } } } }编译执行结果:
D:\src>java ArrayTest4
2
4
6
8
10
12
定义如下图所示的不规则的数组:
图33-3
public class ArrayTest5{ public static void main(String[] args) { int[][] a = new int[3][]; a[0] = new int[2]; a[1] = new int[3]; a[2] = new int[1]; } }
【注意】:int[][] a = new int[3][];不能换写为按列来int[][] a = new int[][3];原因如下如果先定义列的话不知道行数有多少,所以没办法初始化数组,而定义不规整数组时,初始化信息一般从行开始的。
定义一唯数组时可以这样写:int[] a = new int[]{1, 2, 3};
那定义二维数组时也可以这样写:int[][] a = new int[][]{ {1, 2, 3}, {4}, {5, 6, 7, 8} };注意这里面大括号里面的每个大括号表示一行,大括号之间用逗号隔开。具体如下图33-4所示:
图33-4
现在写一个程序将上述数组里面的值打印出来:
int[][] a = new int[][]{ {1, 2, 3}, {4}, {5, 6, 7, 8} }; for(int i = 0; i < a.length; i++){ for(int j = 0; j< a[i].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); }编译执行结果:
D:\src>java ArrayTest5
1 2 3
4
5 6 7 8
【注意】:其中System.out.print();表示输出的时候不换行。这个程序是对所有不规整数组输出内容的通用程序,用这个程序可以打印出所有不规整的数组,其中二维数组的长度length表示二维数组的行数,这个程序先确定有多少行,用length来确定,再从每个一维数组中确定有多少列。