用抽象类排序

时间:2015-09-12 11:07:00

标签: java sorting

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

package BankServices;

public abstract class Operation {

       public Operation (int date, double value){
       }
       public abstract double getValue();
       public abstract int getDate();
       public abstract String toString();
}

package BankServices;

public class Deposit extends Operation {
private int date;
private int value;

public Deposit(int date, double value) {
    super(date, value);
    // TODO Auto-generated constructor stub
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return date + "," + value + "+";
}

@Override
public double getValue() {
    // TODO Auto-generated method stub
    return value;
}

@Override
public int getDate() {
    // TODO Auto-generated method stub
    return date;
}
}
package BankServices;

public class Withdrawal extends Operation{
private int date;
private double value;

public Withdrawal(int date, double value) {
    super(date, value);
    // TODO Auto-generated constructor stub
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return date + "," + value + "-";
}

@Override
public double getValue() {
    // TODO Auto-generated method stub
    return value;
}

@Override
public int getDate() {
    // TODO Auto-generated method stub
    return date;
}   
}

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

public List<Operation> getMovements() {
    Collections.sort(operations, new Comparator<Operation>(){
        public int compare(Operation a, Operation b){
            return (int) (b.getDate() - a.getDate());
        }
    });
    return operations;
}

public List<Deposit> getDeposits() {
    Collections.sort(deposits, new Comparator<Operation>(){
        public int compare(Operation a, Operation b){
            return (int) (b.getValue() - a.getValue());
        }
    });
    return deposits;

}

public List<Withdrawal> getWithdrawals() {
    Collections.sort(withdrawals, new Comparator<Operation>(){
        public int compare (Operation a, Operation b){
            return (int) (b.getValue() - a.getValue());
        }
    });
    return withdrawals;
}

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

1 个答案:

答案 0 :(得分:-1)

而不是SpatialPointsDataFrame使用- compareTo(...)Double上的Date方法,例如:

Collections.sort(withdrawals, new Comparator<Operation>(){
    public int compare (Operation a, Operation b){
        return Double.valueOf(b.getValue()).compareTo(Double.valueOf(a.getValue()));
    }
});

尽管如此,你的代码应该可行,除了你可以拥有的一些奇怪的数据......但我认为不是现实生活中的数据 编辑:我错了,只有当双打之间的差异超过1时,你的代码才有效。