重写.equals()方法的问题

时间:2015-10-17 23:47:28

标签: java junit override

我正在努力在java中覆盖.equals()以获取" Item"带有以下形式的构造函数的类:

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"));

并得到一个断言错误,说它们不相同。乍一看,我很确定我得到了所有东西,但你们有没有看到任何明显的东西?

1 个答案:

答案 0 :(得分:4)

equals()方法中,您将对象实例theOtherthis.getClass()进行了比较,因为您要将实例与类类型进行比较,所以它始终返回false。

根据您的使用情况,您可以使用

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

theOther instanceof Item