简体   繁体   中英

Sorting lists with abstract class

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() {}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM