我有一个类覆盖hashCode()和equals()-method。在处理BigDecimal时,我必须使用compareTo()而不是Objects.equals()
public class MyProduct extends Product{
private BigDecimal price;
@Override
public int hashCode() {
return Objects.hash(price);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // is this right or should this be deleted
if (obj == null || getClass() != obj.getClass()) return false;
final Product other = (Product) obj;
// is this right?
if (price == null ? (other.price != null) : price.compareTo(other.price) != 0) {
return false;
}
return super.equals(obj);
}
}我有以下问题:
equals()-method中删除行-method吗?因为使用这一行,compareTo不会被触发,并且可能计算出一个错误的等于(),对吗?发布于 2019-09-16 22:00:47
第一行只是一个优化,如果两个引用都指向同一个对象,就会提前返回结果。
price可空吗?我假设是这样的,因为您正在equals()实现中检查它。在这种情况下,如果other.price是null,您的代码就不能工作。具体来说,这里的代码是:
price.compareTo(other.price) != 0会抛出一个NullPointerException。
你可以这样解决它:
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // is this right or should this be deleted
if (obj == null || getClass() != obj.getClass()) return false;
final MyProduct other = (MyProduct) obj;
// If you prefer, the below two can be replaced with a single condition
// price != null ^ other.price != null
// Credits to @Andreas
if (price == null && other.price != null) {
return false;
}
if (price != null && other.price == null) {
return false;
}
if (other.price != null && price.compareTo(other.price) != 0) {
return false;
}
return super.equals(obj);
}现在,您可能可以缩短它,但就我个人而言,我认为这是最易读的。
无论如何,除非您真的非常关心定制您的equals()实现,否则我建议用您的IDE生成一个并坚持使用它。他们大部分时间都做得不错,你不必担心它会被破坏(尽管比较BigDecimals对他们来说可能很棘手,因为你不关心规模,而只关心它的价值)。
发布于 2019-09-17 20:48:53
我编写了一个实用的方法,它可以用来比较两个BigDecimals而不抛出NPE:
// returns true, if val1 is the same as val2
// can this be improved ?
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
return !((val1 != null ^ val2 != null) || (val2 != null && val1.compareTo(val2) != 0));
}这可以在等于-方法中使用:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final MyProduct other = (MyProduct) obj;
if(!isEqual(price, other.price)) return false;
return super.equals(obj);
}发布于 2019-09-20 13:58:06
我找到了最简单的方法:
public static boolean isEqual(BigDecimal val1, BigDecimal val2) {
return val1 != null ^ val2 != null && val2 != null && val1.compareTo(val2) != 0;
}然后在equals()中使用它:
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final MyProduct other = (MyProduct) obj;
if(!isEqual(price, other.price)) return false;
return super.equals(obj);
}https://stackoverflow.com/questions/57964739
复制相似问题