Video in progress
Can a HashSet end up with 2 elements and a TreeSet with 1? Explain with BigDecimal.
Yes. new BigDecimal("1.0") and new BigDecimal("1.00") are not equal by equals (the scale differs), but compareTo returns 0. HashSet relies on equals, and TreeSet relies on compareTo.
📖 Answer
var a = new BigDecimal("1.0");
var b = new BigDecimal("1.00");
new HashSet<>(List.of(a, b)).size(); // 2
new TreeSet<>(List.of(a, b)).size(); // 1
The Comparable documentation says it is recommended that the natural ordering be "consistent with equals", meaning compareTo == 0 only when equals == true. BigDecimal breaks this recommendation on purpose.
Where this shows up in practice: if you use amounts as keys in a Map<BigDecimal, ...>, and some places use HashMap while others use TreeMap, the results don't match. Or you compare payments with equals, and 10.00 and 10.0 become "different amounts".
For money, I usually compare with compareTo(...) == 0, or normalize the value with stripTrailingZeros()/setScale(2) first.
Sign up to mark studied questions and save your progress.