覆盖 .equals() 方法的问题

issue with overriding .equals() method

我正在为 "Item" class 覆盖 java 中的 .equals() ,构造函数的形式为:

public Item(final String theName, final BigDecimal thePrice, final int theBulkQuantity,
            final BigDecimal theBulkPrice) {
    myName = Objects.requireNonNull(theName);
    myPrice = Objects.requireNonNull(thePrice);
    myBulkQuantity = theBulkQuantity;
    myBulkPrice = theBulkPrice;

}

使用这个 .equals 方法:

@Override
public boolean equals(final Object theOther) {
    boolean result = false;
    if (this == theOther) {
        result = true;
    }
    else if (theOther != null && theOther == this.getClass()) {
        final Item other = (Item) theOther;

        if ((this.myName.equals(other.myName)) 
            && (this.myBulkQuantity == other.myBulkQuantity)            
            && (this.myPrice.equals(other.myPrice))
            && (this.myBulkPrice.equals(other.myBulkPrice))) {
            result = true;
        }                        
    }    
    return result;
}

我是一名计算机科学专业的新学生,这是我第一次尝试覆盖。如果我没有使用以下方法使用 JUnit 测试,我会忽略这一点:

testItemB = new Item("ItemB", new BigDecimal("5.00"), 5, new BigDecimal("20.00"));
testItemC = new Item("ItemB", new BigDecimal("5.00"), 5, new BigDecimal("20.00"));

并得到一个断言错误,说它们不等价。乍一看,我很确定我得到了所有东西,但是你们碰巧看到了什么刺眼的东西吗?

equals() 方法中,您将对象实例 theOtherthis.getClass() 进行了比较,这将始终 return false 因为您正在将实例与 class 类型。

根据您的用例,您可以使用

obj1.getClass().equals(obj2.getClass())

theOther instanceof Item