关于equals 和 compareTo函数

今天,在JavaDoc上查询了一下,发现用equals不能判断两个BigDecimal数值是否相等。
equals

public boolean equals(Object x)
Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimals equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
Overrides:
equals in class Object
Parameters:
x - Object to which this BigDecimal is to be compared.
Returns:
true if and only if the specified Object is a BigDecimal whose value and scale are equal to this BigDecimal's.

compareTo

public int compareTo(BigDecimal val)
Compares this BigDecimal with the specified BigDecimal. Two BigDecimals that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.
Parameters:
val - BigDecimal to which this BigDecimal is to be compared.
Returns:
-1, 0 or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

从Doc中可以看出,当BigDecimal类型用equals做比较时,需要Scale相等,否则BigDecimal.equals(Object o),返回0;
而compareTo则不考虑Scale。所以,BigDecimal类型比较用CompareTo函数。

你可能感兴趣的:(compareTo)