[英]Sorting with abstract class
我在按降序对以下抽象类及其扩展的元素进行排序时遇到了一些困难。
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;
}
第一个返回按日期排序的列表,而 getDeposits() 和 getWithdrawals() 返回按值排序的列表和列表..您能否建议如何使其正常工作而不会出错和失败? 非常感谢您提前。
而不是这个-
使用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()));
}
});
尽管如此,你的代码应该可以工作,除了一些你可以在那里拥有的奇怪数据......但我认为不适用于现实生活中的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.