From fd0b9726ca2794fc9615233069538548a97f9d82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cidpeng=E2=80=9D?= <630606938@qq.com> Date: Mon, 30 Aug 2021 22:24:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=88x=E5=86=8Dy=EF=BC=8C=E4=BB=8E=E5=B0=8F?= =?UTF-8?q?=E5=88=B0=E5=A4=A7=E7=9A=84=E9=A1=BA=E5=BA=8F=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/hcsp/polymorphism/Point.java | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/hcsp/polymorphism/Point.java b/src/main/java/com/github/hcsp/polymorphism/Point.java index 780e6b1..63bbb45 100644 --- a/src/main/java/com/github/hcsp/polymorphism/Point.java +++ b/src/main/java/com/github/hcsp/polymorphism/Point.java @@ -2,12 +2,15 @@ import java.io.IOException; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.List; -public class Point { +public class Point implements Comparable { private final int x; private final int y; + // 代表笛卡尔坐标系中的一个点 public Point(int x, int y) { this.x = x; @@ -53,7 +56,10 @@ public String toString() { // 按照先x再y,从小到大的顺序排序 // 例如排序后的结果应该是 (-1, 1) (1, -1) (2, -1) (2, 0) (2, 1) - public static List sort(List points) {} + public static List sort(List points) { + Collections.sort(points); + return points; + } public static void main(String[] args) throws IOException { List points = @@ -65,4 +71,20 @@ public static void main(String[] args) throws IOException { new Point(2, -1)); System.out.println(Point.sort(points)); } + + @Override + public int compareTo(Point that) { + if (this.x < that.x) { + return -1; + } else if (this.x > that.x) { + return 1; + } else { + if (this.y < that.y) { + return -1; + } else if (this.y > that.y) { + return 1; + } + return 0; + } + } }