Java 从入门到进阶之路(九),Java 中的引用型数组类型。
之前的文章我们介绍了一下 Java 中的构造方法,接下来我们再来看一下 Java 中的引用型数组类型。
现在我们想定义一个坐标系,然后通过横坐标(row)和纵坐标(col)来确定一个坐标点,代码如下:
1 public class HelloWorld {
2 public static void main(String[] args) {
3 Point p1 = new Point(1, 2);
4 p1.print(); // (1,2)
5
6 Point p2 = new Point(3, 4);
7 p2.print(); // (3,4)
8
9 }
10 }
11
12 class Point {
13 int row;
14 int col;
15
16 Point(int row, int col) {
17 this.row = row;
18 this.col = col;
19 }
20
21 void print() {
22 System.out.print("(" + row + "," + col + ")");
23 }
24
25 }
通过以上代码我们可以获取坐标系上的某个点,如(1,2)或(3,4),但是如果我们想获取一个点的坐标集合,如:[(1,2),(3,4),(5,6),(7,8)],那该如何实现呢。
我们先来看一下之前说过的 int 型数组。
1 public class HelloWorld {
2 public static void main(String[] args) {
3 int[] arr = new int[4];
4 arr[0] = 11;
5 arr[1] = 22;
6 arr[2] = 33;
7 arr[3] = 44;
8 for (int i = 0; i < arr.length; i++) {
9 System.out.println(arr[i]); // 11 22 33 44
10 }
11
12 }
13 }
在上面的代码中我们通过 int[] arr = new int[4]; 创建了一个长度为 4 的 int 型数组,那么我们不就可以通过 Point[] points = new 来创建一个长度为 4 的 Point 型数组嘛,然后我们再通过 new
1 public class HelloWorld {
2 public static void main(String[] args) {
3 Point[] points = new Point[4];
4 points[0] = new Point(1, 2);
5 points[1] = new Point(3, 4);
6 points[2] = new Point(5, 6);
7 points[3] = new Point(7, 8);
8 for (int i = 0; i < points.length; i++) {
9 points[i].print(); // (1,2) (3,4) (5,6) (7,8)
10 }
11
12 }
13 }
14
15 class Point {
16 int row;
17 int col;
18
19 Point(int row, int col) {
20 this.row = row;
21 this.col = col;
22 }
23
24 void print() {
25 System.out.print("(" + row + "," + col + ")");
26 }
27
28 }
从输出结果可以看出完全符合我们的预期。
当然,在 int 型数组赋值时我们可以通过 int[] arr = new int[]{ }
1 public class HelloWorld {
2 public static void main(String[] args) {
3 int[] arr = new int[]{
4 11,
5 22,
6 33,
7 44
8 };
9
10 for (int i = 0; i < arr.length; i++) {
11 System.out.println(arr[i]); // 11 22 33 44
12 }
13
14 }
15 }
那我们同样可以将 Point 型数组修改成 Point points = new
1 public class HelloWorld {
2 public static void main(String[] args) {
3 Point[] points = new Point[]{
4 new Point(1, 2),
5 new Point(3, 4),
6 new Point(5, 6),
7 new Point(7, 8)
8 };
9
10 for (int i = 0; i < points.length; i++) {
11 points[i].print(); // (1,2) (3,4) (5,6) (7,8)
12 }
13
14 }
15 }
16
17 class Point {
18 int row;
19 int col;
20
21 Point(int row, int col) {
22 this.row = row;
23 this.col = col;
24 }
25
26 void print() {
27 System.out.print("(" + row + "," + col + ")");
28 }
29
30 }