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 4410 } 11 12 } 13 }
在上面的代码中我们通过