繁体   English   中英

覆盖.equals()方法的问题

[英]issue with overriding .equals() method

我正在使用构造函数以以下形式构造Java中的“ Item”类重写.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()方法中,您将对象实例theOthertheOther this.getClass()进行了比较,由于您正在将实例与类类型进行比较,该对象将始终返回false。

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

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

要么

theOther instanceof Item

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM