
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 Point[4]; 來建立一個長度為 4 的 Point 型數組嘛,然後我們再通過 new Point(1,2) 這樣的形式來分别給 Point 型數組内指派就可以了,如下:
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 Point[]{ } ,如下:
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 }