用抽象类对列表进行排序

编程入门 行业动态 更新时间:2024-10-23 02:04:16
本文介绍了用抽象类对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在将以下抽象类及其扩展的元素降序排序时,我遇到了一些困难.

I had some difficulties in sorting in decreasing order the elements of the following abstract class and its extensions.

package BankServices; public abstract class Operation { public abstract String toString(); } package BankServices; public class Deposit extends Operation implements Comparable{ private int date; //date on which the deposit was made private double value; //deposit value public Deposit (int date, double value){ this.date = date; this.value = value; } public double getValue(){ return value; } @Override public String toString() { // TODO Auto-generated method stub return date+ "," + value+ "+"; } } package BankServices; public class Withdrawal extends Operation{ private int date; //date on which the sum (value) has been withdrawn private double value; public Withdrawal (int date, double value){ this.date = date; this.value = value; } public double getValue(){ return value; } @Override public String toString() { // TODO Auto-generated method stub return date + "," + value + "-"; } }

` 我必须实现主类按降序返回排序列表的这些方法:

` I had to implement these methods of the main class returning sorted lists in descending order:

public List<Operation> getMovements() {} public List<Deposit> getDeposits() {} public List<Withdrawal> getWithdrawals() {}

第一个返回按日期排序的List,而getDeposits()和getWithdrawals()返回按值排序的List和List. 您能否建议如何使它正常工作而没有错误和失败? 提前非常感谢您.

the first one returns a List ordered by date, while getDeposits() and getWithdrawals() return List and List ordered by value.. Could you please suggest how to make it work without mistakes and failures? Thank you very much in advance.

推荐答案

您可以使用Collection.sort并根据需要每次给它一个新的比较器:

You can use Collection.sort and give it each time a new comparator based on your need:

Collections.sort(yourList, new Comparator<Operation>(){ public int compare(Operation o1, Operation o2) { //Here implement each comparator as you need }

请记住,您可能需要将日期和值推入操作超类,因为它们在两个子类中都是通用的,您将在比较器中使用它们.

Keep in mind that you may need to push date and value to the operation superclass since they are common in both subclasses and you will use them in the comparator.

更多推荐

用抽象类对列表进行排序

本文发布于:2023-10-15 02:50:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493027.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抽象类   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!