Java 重写.equals()方法时出现问题
我正在为一个“Item”类在java中重写.equals(),该类的构造函数形式如下:Java 重写.equals()方法时出现问题,java,junit,overriding,Java,Junit,Overriding,我正在为一个“Item”类在java中重写.equals(),该类的构造函数形式如下: public Item(final String theName, final BigDecimal thePrice, final int theBulkQuantity, final BigDecimal theBulkPrice) { myName = Objects.requireNonNull(theName); myPrice = Objects.requi
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()
方法中,您将对象实例与另一个进行了比较与this.getClass()
,因为您正在将实例与类类型进行比较,因此该方法将始终返回false
根据您的用例,您可以使用
obj1.getClass().equals(obj2.getClass())
或
比我快:)回答得好。@Dinesh我明白问题所在。虽然我用theOther.getClass()
替换了theOther
,但这似乎使它能够工作。希望这不是侥幸。
theOther instanceof Item