While going through compareTo(T o) method in the Comparable interface, I came across a very interesting finding of BigDecimal equals versus compareTo and though about sharing about it.
Usually, we require that two objects are equal if and only if they are compared as same
For BigDecimal things are really interesting when we check both equals() and compareTo() method
Consider following small program
BigDecimal x = new BigDecimal("2"); BigDecimal y = new BigDecimal("2.00"); System.out.println(x.equals(y)); System.out.println(x.compareTo(y) == 0 ? "true": "false");
We can say that x is equal to y (not object reference), running the above program will show following out
One of the questions that came to my mind while checking this out is “How compareTo determine that x is equal to y for BigDecimal and what is the difference between compareTo() and equals() methods in BigDecimal”
The answer was in JavaDoc of the equals() method:
Compares this BigDecimal with the specified Object for equality. Unlike compareTo , this method considers two 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). equals methods takes scale into consideration
To summarise, equals() check if BigDecimal objects are same is every aspect while compareTo only check for numeric values.
run following code and check the output
BigDecimal x = new BigDecimal(2); BigDecimal y = new BigDecimal(2.00); System.out.println(x.equals(y)); System.out.println(x.compareTo(y) == 0 ? "true": "false");
This is a tricky part of BigDecimal, if you do not have clarity of this and implement it incorrectly, it can lead to many strange bug/issues in your code.
Bottom line is
Use compareTo() instead of equals() to compare numeric values since equals() takes scale into consideration