【发布时间】:2020-12-02 03:17:09
【问题描述】:
我正在使用比较器接口来比较自定义对象以对 ArrayList 进行排序。这适用于 int 和 String 值,但是当我想对双精度进行排序/比较时,我遇到了麻烦。
我知道 Java 在我的方法中四舍五入并将 1.7、1.62、1.66 读取为 1,这是错误。
但我似乎无法找到解决此问题的方法。这是我的方法和结果 - 结果表明,由于将 double 转换为 int,Comparator 无法正确排序列表。
请注意,我的“赔率”变量是双倍值,必须在比较器接口中转换为函数:
public Integer getOddsInt() {
return (int) odds;
}
public class SortOdds implements Comparator <History>{
public int compare(History a, History b)
{
return a.getOddsInt() - b.getOddsInt();
}
}
结果:
[
2.62 |
, 1.7 |
, 1.62 |
, 1.66 |
]
【问题讨论】:
标签: java arraylist type-conversion compare