How to make Lombok#39;s EqualsAndHashCode work with BigDecimal(如何让Lombok的EqualsAndHashCode与BigDecimal一起工作)
问题描述
我正好有here描述的问题。这就是说,如果BigDecimal
的等号被破坏,那么在类中有这样的字段就无法使用@EqualsAndHashCode
。我想出的唯一解决方案就是使用exclude
这样的字段,但这当然不是最优的。
有什么解决办法吗?有没有办法为字段/类型插入我自己的比较器?
推荐答案
我最近遇到了同样的问题。
基本上,您会看到以下行为:
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
没有开箱即用的好解决方案,但您可以重新定义hashCode&;equals:
中使用的BigDecimal字段值@EqualsAndHashCode
class Test Class {
@EqualsAndHashCode.Exclude
private BigDecimal amount;
...
@EqualsAndHashCode.Include
private BigDecimal getAmountForEquals() {
return ofNullable(amount).map(BigDecimal::stripTrailingZeros).orElse(null);
}
}
这篇关于如何让Lombok的EqualsAndHashCode与BigDecimal一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!