我有这个:
// returns true if both are equal (independent of scale) and also checks against null
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
// 1. check: both will be null or both will be non-null.
if (val1 != null ^ val2 != null) return false;
// 2. check: if not null, then compare if both are equal
return !(val2 != null && val1.compareTo(val2) != 0);
}
我想将布尔表达式合并为一个。因此我使用了以下代码:
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
return !(val1 != null ^ val2 != null) && !(val2 != null && val1.compareTo(val2) != 0);
}
然而,我担心这是否正确。这个正确吗?能否简化或缩短?
借助答案的帮助,简化的解决方案是:
// returns true, if both are null or both are equal
// (independent of their numbers scales)
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
return val1 == null ? val2 == null : val2 != null && val1.compareTo(val2) == 0;
}