这不是关于如何比较两个BigDecimal对象的问题 - 我知道你可以使用compareTo而不是equals这样做,因为equals记录为:
与compareTo不同,此方法仅考虑两个BigDecimal对象的值和比例相等(因此通过此方法比较时2.0不等于2.00).
问题是:为什么equals以这种看似违反直觉的方式指定了?也就是说,为什么能够区分2.0和2.00 很重要?
似乎必须有这样的理由,因为Comparable指定compareTo方法的文档指出:
强烈建议(尽管不要求)自然排序与equals一致
我想必须有一个很好的理由忽略这个建议.
我有来自两家公司asoft和bsoft的代码.我也无法改变.这是我的情况的简化版本,我非常确定有足够的信息来查找导致问题的原因.
bsoft提供IGang,代表一个可以与其他帮派作战的团伙.
package bsoft;
public interface IGang {
/** @return negative, 0, or positive, respectively
* if this gang is weaker than, equal to, or stronger
* than the other
*/
public int compareTo(IGang g);
public int getStrength();
public String getName();
public void attack(IGang g);
public void weaken(int amount);
}
Run Code Online (Sandbox Code Playgroud)
asoft提供GangWar,允许IGangs战斗:
package asoft;
import java.util.*;
import bsoft.*;
/** An `IGang` ordered by identity (name) */
public interface ComparableGang extends IGang, Comparable<IGang> {}
package asoft; …Run Code Online (Sandbox Code Playgroud)