如何用comparable<T>接口,按照账户余额比较账户大小;同时用ComparaeName,比较账户名大小
1条回答 默认 最新
- threenewbee 2023-06-08 09:28关注
public class Account implements Comparable<Account> { private String name; private double balance; @Override public int compareTo(Account other) { if(this.balance > other.balance) { return 1; } else if(this.balance < other.balance) { return -1; } else { return 0; } } } public class CompareName implements Comparator<Account> { @Override public int compare(Account acc1, Account acc2) { return acc1.getName().compareTo(acc2.getName()); } } public class CompareTest { public static void main(String[] args) { List<Account> accounts = new ArrayList<>(); accounts.add(new Account("Alice", 1000)); accounts.add(new Account("Bob", 2000)); accounts.add(new Account("Charlie", 3000)); Collections.sort(accounts); // 按余额排序 System.out.println("按余额排序:"); for(Account account : accounts) { System.out.println(account.getName() + ": " + account.getBalance()); } System.out.println(); CompareName compareName = new CompareName(); Collections.sort(accounts, compareName); // 按名字排序 System.out.println("按名字排序:"); for(Account account : accounts) { System.out.println(account.getName() + ": " + account.getBalance()); } } }
解决评论 打赏 举报无用 1
悬赏问题
- ¥15 python怎么在已有视频文件后添加新帧
- ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
- ¥15 fluent里模拟降膜反应的UDF编写
- ¥15 MYSQL 多表拼接link
- ¥15 关于某款2.13寸墨水屏的问题
- ¥15 obsidian的中文层级自动编号
- ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
- ¥15 神经网络模型一直不能上GPU
- ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
- ¥20 wpf datagrid单元闪烁效果失灵