2015-10-17 46 views
2

我工作的形式覆盖.equals()在Java中的一个“项目”类与构造函数:使用此方法.equals问题与压倒一切的.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; 

} 

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

,并得到断言错误说他们是不等价的。乍一看,我很确定我得到了一切,但你们是否碰巧看到任何明显的东西?

回答

4

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

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

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

theOther instanceof Item 
+0

打我吧:)好答案。 – Siddhartha

+0

@Dinesh我看到了问题。尽管我用'theOther.getClass()'替代了'theOther',这似乎使它工作。希望这不是侥幸。 –