I have exactly the problem described here. This is, being BigDecimal
's equals being broken as it is, having such a field in a class prevents using @EqualsAndHashCode
. The only solution I came up with is to exclude
such fields, but of course this is not optimal.
Is there any solution? Any way of injecting my own comparator for a field/type?
I faced the same issue recently.
Basically, you see this behavior:
BigDecimal x = new BigDecimal("2");
BigDecimal y = new BigDecimal("2.00");
System.out.println(x.equals(y)); // False
System.out.println(x.compareTo(y) == 0 ? "true": "false"); // True
There's no a good solution that will work out of the box, but you may redefine BigDecimal field value being used in hashCode & equals:
@EqualsAndHashCode
class Test Class {
@EqualsAndHashCode.Exclude
private BigDecimal amount;
...
@EqualsAndHashCode.Include
private BigDecimal getAmountForEquals() {
return ofNullable(amount).map(BigDecimal::stripTrailingZeros).orElse(null);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With