Skip to content

Commit aa0f654

Browse files
authored
sort-by-multiple-fields (#213)
sort-by-multiple-fields (#213)
1 parent 516838e commit aa0f654

File tree

1 file changed

+23
-2
lines changed
  • src/main/java/com/github/hcsp/polymorphism

1 file changed

+23
-2
lines changed

src/main/java/com/github/hcsp/polymorphism/Point.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
import java.io.IOException;
44
import java.util.Arrays;
5+
import java.util.Collections;
56
import java.util.List;
67

7-
public class Point {
8+
public class Point implements Comparable<Point>{
89

910
private final int x;
1011
private final int y;
12+
1113
// 代表笛卡尔坐标系中的一个点
1214
public Point(int x, int y) {
1315
this.x = x;
@@ -53,7 +55,10 @@ public String toString() {
5355

5456
// 按照先x再y,从小到大的顺序排序
5557
// 例如排序后的结果应该是 (-1, 1) (1, -1) (2, -1) (2, 0) (2, 1)
56-
public static List<Point> sort(List<Point> points) {}
58+
public static List<Point> sort(List<Point> points) {
59+
Collections.sort(points);
60+
return points;
61+
}
5762

5863
public static void main(String[] args) throws IOException {
5964
List<Point> points =
@@ -65,4 +70,20 @@ public static void main(String[] args) throws IOException {
6570
new Point(2, -1));
6671
System.out.println(Point.sort(points));
6772
}
73+
74+
@Override
75+
public int compareTo(Point that) {
76+
if (this.x < that.x) {
77+
return -1;
78+
} else if (this.x > that.x) {
79+
return 1;
80+
}
81+
if (this.y < that.y) {
82+
return -1;
83+
} else if (this.y > that.y) {
84+
return 1;
85+
}
86+
return 0;
87+
88+
}
6889
}

0 commit comments

Comments
 (0)