使用抽象类对列表进行排序

时间:2015-09-12 08:11:29

标签: java sorting

我在按顺序排序以下抽象类及其扩展的元素时遇到了一些困难。

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 + "-";
 } 
 }

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

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

第一个返回按日期排序的List,而getDeposits()和getWithdrawals()返回按值排序的List和List。 你能否建议如何让它在没有错误和失败的情况下工作? 非常感谢你提前。

1 个答案:

答案 0 :(得分:1)

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

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

请记住,您可能需要将日期和值推送到操作超类,因为它们在两个子类中都很常见,您将在比较器中使用它们。