2014-02-10 57 views
0

我试图做一个有理数的类,并重写equals和hash代码的方法。但是,我的平等在这种情况下会回归真实,即它的分子和分母是不同的。任何想法可能会造成这种情况?覆盖等于方法问题

public boolean equals(Object rhs) { 
    if (this == rhs){ 
     return true; 
    } 
    if (rhs == null){ 
     return false; 
    } 
    if (!(rhs instanceof Rational)){ 
     return false; 
    } 
    Rational other = (Rational) rhs; 
    if (denom == other.denom){ 
     if (num == other.num);{ 
      return true; 
     } 
    } 
    return false; 
} 

回答

4

这是问题(如果不是笔误):

if (num == other.num);{ 

分号指if语句是空语句,所以它的评价并没有真正涉足平等的验证过程。只需删除分号:

if (num == other.num){ 
1

删除此行上的分号,该行用作if语句的主体。

if (num == other.num);{ 

随着分号,如果分母相等,则true将被退回;分子的检查被有效地忽略。

+0

就这样做了。谢谢你发现 –

1

取出;if (num == other.num); {后,它changint到if (num == other.num) {

离开它在那里,它基本上在if后什么都没有,然后进入块:

{ 
    return true; 
} 

所以它总是会在那返回true点。