Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Lombok's EqualsAndHashCode work with BigDecimal

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?

like image 837
user3748908 Avatar asked Apr 14 '16 13:04

user3748908


1 Answers

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);
  }
}
like image 108
Leonid Dashko Avatar answered Oct 28 '22 14:10

Leonid Dashko