Skip to content

Commit feb54b5

Browse files
按照多重字段排序
1 parent d9b1d25 commit feb54b5

File tree

1 file changed

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

1 file changed

+26
-2
lines changed

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

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
package com.github.hcsp.polymorphism;
22

3+
import javafx.print.Collation;
4+
35
import java.io.IOException;
46
import java.util.Arrays;
7+
import java.util.Collections;
58
import java.util.List;
69

7-
public class Point {
10+
public class Point implements Comparable<Point> {
811

912
private final int x;
1013
private final int y;
14+
1115
// 代表笛卡尔坐标系中的一个点
1216
public Point(int x, int y) {
1317
this.x = x;
@@ -53,7 +57,11 @@ public String toString() {
5357

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

5866
public static void main(String[] args) throws IOException {
5967
List<Point> points =
@@ -65,4 +73,20 @@ public static void main(String[] args) throws IOException {
6573
new Point(2, -1));
6674
System.out.println(Point.sort(points));
6775
}
76+
77+
@Override
78+
public int compareTo(Point o) {
79+
if (this.x < o.x) {
80+
return -1;
81+
} else if (this.x > o.x) {
82+
return 1;
83+
}
84+
85+
if (this.y < o.y) {
86+
return -1;
87+
} else if (this.y > o.y) {
88+
return 1;
89+
}
90+
return 0;
91+
}
6892
}

0 commit comments

Comments
 (0)