day02 No.1自定义CompareTo排序

该代码示例展示了一个Java类,该类实现了Comparable接口以进行自定义排序。类包含两个变量x和y,并根据给定条件(x降序,x相同则y升序)进行排序。在Test类的main方法中,创建了此类的对象数组并使用Arrays.sort进行排序,然后打印排序后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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());
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值