BigDecimal等于()与compareTo() [英] BigDecimal equals() versus compareTo()
问题描述
考虑简单的测试类:
import java.math.BigDecimal;
/**
* @author The Elite Gentleman
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BigDecimal x = new BigDecimal("1");
BigDecimal y = new BigDecimal("1.00");
System.out.println(x.equals(y));
System.out.println(x.compareTo(y) == 0 ? "true": "false");
}
}
你可以(有意识地)说出来 x
等于 y
(不是对象引用),但是当您运行程序时,以下结果显示:
You can (consciously) say that x
is equal to y
(not object reference), but when you run the program, the following result shows:
false
true
问题: compareTo()
和等于()
在<$中有什么区别? c $ c> BigDecimal compareTo
可以确定 x
等于 y
?
Question: What's the difference between compareTo()
and equals()
in BigDecimal
that compareTo
can determine that x
is equal to y
?
PS:我看到BigDecimal有 inflate()
上的方法equals()
方法。 inflate()
实际上做了什么?
PS: I see that BigDecimal has an inflate()
method on equals()
method. What does inflate()
do actually?
推荐答案
答案是 <$ c $的JavaDoc c> equals()方法:
与
compareTo
,此方法只考虑两个BigDecimal
对象,只有它们在值和比例上相等(因此通过此方法比较时2.0不等于2.00)。
Unlike
compareTo
, this method considers twoBigDecimal
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).
换句话说: equals()
检查 BigDecimal
对象完全在每个方面相同。 compareTo()
only比较它们的数值。
In other words: equals()
checks if the BigDecimal
objects are exactly the same in every aspect. compareTo()
"only" compares their numeric value.
这篇关于BigDecimal等于()与compareTo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!