import java.util.Arrays;
import java.util.Scanner;
public class Demo {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
MyPoint[] points = new MyPoint[n];
for (int i = 0; i < n; i++) {
points[i] = new MyPoint(in.nextInt(), in.nextInt());
}
Arrays.sort(points);
//System.out.println("排序后:");
for (int i = 0; i < n; i++) {
System.out.println(points[i].x + " " + points[i].y);
}
in.close();
}
}
class MyPoint implements Comparable<MyPoint> {
public int x;
public int y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(MyPoint other) {
if (this.x > other.x) {
return 1;
} else if (this.x < other.x) {
return -1;
} else if (this.y > other.y) {
return 1;
} else if (this.y < other.y) {
return -1;
}
return 0;
}
}
运行示例:
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/810a19d8bc3eb13588146f4aa01ea8d3fc1f4474?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
追问你运行了啊
看不明白
能稍微解释一下吗 谢谢哦
追答就是说定义一个类 MyPoint,它包含 x 和 y 两个值。这个类实现了 Comparable<MyPoint> 接口,<MyPoint> 表示比较的时候是 当前实例和另一个 MyPoint 的实例进行比较。比较的规则就是下面的代码:
if (this.x > other.x) {
return 1;
} else if (this.x < other.x) {
return -1;
} else if (this.y > other.y) {
return 1;
} else if (this.y < other.y) {
return -1;
}
return 0;
}
这个规则就是你题目要的那个效果。
然后 Arrays.sort 方法可以对实现了Comparable 接口的类对数组进行排序,根据 compareTo 方法来排(我们自己在这个方法里定义的排序规则)。
追问好的 谢谢你哦
你能稍微跟我讲一下comparable《mypoint》接口是什么意思吗?我还没学到那里 谢谢
在
我的有错误啊?
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/d439b6003af33a87f58a0ee8c05c10385243b558?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)