来自 BigDecimal 的 OpenJDK 实现:
/**
* Compares this {@code BigDecimal} with the specified
* {@code Object} for equality. Unlike {@link
* #compareTo(BigDecimal) compareTo}, this method considers two
* {@code BigDecimal} objects equal only if they are equal in
* value and scale (thus 2.0 is not equal to 2.00 when compared by
* this method).
*
* @param x {@code Object} to which this {@code BigDecimal} is
* to be compared.
* @return {@code true} if and only if the specified {@code Object} is a
* {@code BigDecimal} whose value and scale are equal to this
* {@code BigDecimal}'s.
* @see #compareTo(java.math.BigDecimal)
* @see #hashCode
*/
@Override
public boolean equals(Object x) {
if (!(x instanceof BigDecimal))
return false;
BigDecimal xDec = (BigDecimal) x;
if (x == this)
return true;
if (scale != xDec.scale)
return false;
long s = this.intCompact;
long xs = xDec.intCompact;
if (s != INFLATED) {
if (xs == INFLATED)
xs = compactValFor(xDec.intVal);
return xs == s;
} else if (xs != INFLATED)
return xs == compactValFor(this.intVal);
return this.inflate().equals(xDec.inflate());
}
更多来自实现:
* <p>Since the same numerical value can have different
* representations (with different scales), the rules of arithmetic
* and rounding must specify both the numerical result and the scale
* used in the result's representation.
这就是为什么实施要考虑的原因。将字符串作为参数的构造函数实现如下:equals
scale
public BigDecimal(String val) {
this(val.toCharArray(), 0, val.length());
}
其中第三个参数将用于(在另一个构造函数中),这就是为什么字符串和将创建不同的BigDecimals(具有不同的刻度)。scale
1.0
1.00
来自 Effective Java by Joshua Bloch:
compareTo合约的最后一段,这是一个强有力的建议,而不是一个真正的规定,它只是说,由compareTo方法施加的相等性测试通常应该返回与equals方法相同的结果。如果遵守这一规定,则 compareTo 方法强加的顺序称为与 equals 一致。如果违反,则称排序与 equals 不一致。其 compareTo 方法施加的顺序与 equals 不一致的类仍将有效,但包含该类元素的排序集合可能不遵守相应集合接口(集合、集或映射)的一般协定。这是因为这些接口的一般协定是根据 equals 方法定义的,但排序的集合使用 compareTo 施加的相等性测试来代替 equals。如果发生这种情况,这不是一场灾难,但这是需要注意的。