再会。
任务:有以下类
public class Products {
public final Product PRODUCT;
public final double AMOUNT;
public final BigDecimal PRICE;
public final BigDecimal CALORIES;
public Products(Product product,
double amount,
BigDecimal price,
BigDecimal calories) {
PRODUCT = product;
AMOUNT = amount;
PRICE = price;
CALORIES = calories;
}
}
必须重写此类的 equals() 和 hashCode() 方法。所有字段都必须参与覆盖的方法。最重要的是,在比较 PRICE 和 CALORIES 字段时,有必要只比较值而不考虑比例,即 比较两个 BigDecimal 值 12 和 12.000000 应该返回 true。
我如何尝试解决问题:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Products that = (Products) o;
return Double.compare(that.AMOUNT, AMOUNT) == 0 &&
Objects.equals(PRODUCT, that.PRODUCT) &&
PRICE.compareTo(that.PRICE) == 0 &&
CALORIES.compareTo(that.CALORIES) == 0;
}
@Override
public int hashCode() {
int result = 17;
result = result * 31 + PRODUCT.hashCode();
result = result * 31 + Double.hashCode(AMOUNT);
result = result * 31 + PRICE.hashCode();
result = result * 31 + CALORIES.hashCode();
return result;
}
问题出在哪里:equals() 方法比较 BigDecimal 不考虑比例,而 hashCode() 使用 BigDecimal::hashCode() 计算值是有比例的。
问题:如何计算没有比例的 BigDecimal 的 hashCode?
我会从相反的方向走。在现实生活中,您不能有任意小数位数的价格。卡路里和数量也是如此(我也会将数量存储在 中
BigDecimal)。您可以在构造函数中强制设置所需的比例,之后
hashCode()您将拥有相同的价格、卡路里含量、数量。方法不变
equals。hashCode你可以取
doubleValue然后BigDecimal取hash