Video in progress
Why do `HashSet` and `TreeSet` report different sizes in this code?
var a = new BigDecimal("2.0");
var b = new BigDecimal("2.00");
Set<BigDecimal> hash = new HashSet<>(List.of(a, b));
Set<BigDecimal> tree = new TreeSet<>(List.of(a, b));
System.out.println(hash.size() + " " + tree.size()); // 2 1
BigDecimal.equals compares the scale as well as the value, so 2.0 and 2.00 are not equal. HashSet relies on equals/hashCode and keeps two elements; TreeSet relies on compareTo and treats them as one.
📖 Answer
a.equals(b) is false (scale 1 vs 2), while a.compareTo(b) is 0. In other words, BigDecimal's compareTo is "inconsistent with equals". The Comparable javadoc allows this, but warns that sorted collections then violate the Set contract.
On prod it looks like this: you deduplicate a list of prices with a HashSet, the database gives you 2.00, the API gives you 2.0, and you get a duplicate. Or a sum can't be found under a Map<BigDecimal, ...> key. A test like assertEquals(new BigDecimal("10"), result) also fails if the result is 10.00.
What to do:
- compare money with
compareTo(...) == 0, notequals; - normalize the scale before using a value as a key:
setScale(2, RoundingMode.HALF_UP)orstripTrailingZeros(); - best of all, use a
Moneyvalue object: the scale is always normalized inside according to the currency, and you writeequalsyourself.
If you implement Comparable in your own class, the rule is: when compareTo returns 0, equals should return true too. Otherwise, document it clearly in the javadoc.
Sign up to mark studied questions and save your progress.