package lanqiao;
import java.util.Arrays;
public class normal类的结构体排序 implements Comparable<normal类的结构体排序> {
int x, y;
//某类有x、y两个变量,先按x降序排(大于返回-1),x相同则按y升序排(大于返回1,默认就是升序)
public normal类的结构体排序(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return this.x + " " + this.y;
}
//对比后面对象(this)与前面对象(o)的大小
@Override
public int compareTo(normal类的结构体排序 o) {
// if (this.x > o.x)
// return -1;// this.x > o.x 返回-1,则表示从大到小排,正常默认是升序(返回1)
// else if(this.x < o.x) {
// return 1;
// }
// else {
// return this.y - o.y;//缩写,后面大前面小升序,想降序加个负号
// }
//与上等价
if(this.x!=o.x)
return o.x - this.x;
else
return this.y - o.y;
}
}
class Test {
public static void main(String[] args) {
normal类的结构体排序 n[] = new normal类的结构体排序[5];
n[0] = new normal类的结构体排序(2, 2);
n[1] = new normal类的结构体排序(3, 3);
n[2] = new normal类的结构体排序(3, 2);
n[3] = new normal类的结构体排序(3, 100);
n[4] = new normal类的结构体排序(5, -1);
Arrays.sort(n);
for (int i = 0; i < 5; i++) {
System.out.println(n[i].toString());
}
}
}
day02 No.1自定义CompareTo排序
于 2023-03-24 18:05:44 首次发布