2011-09-12 19 views
1

我有我自己的類,它是一個其中有一組其他對象的對象。 即自己的對象和.equals的Java集合

public class Curve{ 


@Override 
public Collection<CurvePoint> getCurvePoints() { 
return curvePoints; 
} 

@Override 
public boolean equals(Object other) { 
    if (other instanceof Curve) { 
     Curve otherCurve = (Curve) other; 
     return getCurvePoints().equals(otherCurve.getCurvePoints()); 
    } 
    return false; 
}   
} 

其中CurvePoint類implments可比性,也覆蓋,像這樣的equals方法:

public class CurvePoint implements ICurvePoint, Comparable<CurvePoint> { 

@Override 
    public int compareTo(CurvePointother) { 

     return getSnapDate().compareTo(other.getSnapDate()); 

    } 
@Override 
    public boolean equals(Object other) { 
     if (other instanceof CurvePoint) { 
      CurvePointotherPoint = (CurvePoint) other; 

      return (getId().equals(otherPoint.getId()) 
        && getBid().getRate() == otherPoint.getBid().getRate() 
        && getOffer().getRate() == otherPoint.getOffer().getRate() && getMid() 
        .getRate() == otherPoint.getMid().getRate()); 
     } 
     return false; 
    } 

} 

我的問題是,當我有曲線的2個集,如何比較這些檢查如果他們平等?當我使用.equals時,它總是返回false,有沒有辦法做到這一點,而不需要循環兩個集合?

+1

沒有。 equals()標準集合的實現總是比較所有的孩子。其他一切都會很糟糕 –

回答

0

如果你正在比較集合,那麼集合需要有一個可比較的接口,它爲集合做了正確的事情。

基本上有可能,但是如果當前集合沒有按照您喜歡的方式實現比較,則需要繼承該集合並覆蓋方法compareTo(...)equals(...)

+0

基本上我已經覆蓋了我的curvePoint中的compareTo()方法,因爲我希望它們根據我的曲線中的排序集中的日期進行排序。我認爲集合上的哪些.equals會循環並調用.compareTo,因爲我希望它使用.equals。有沒有辦法做到這一點? – Twinhelix

0

既然你沒有表現出CurvePoint的整個代碼只是檢查:getBid()的getRate()和都做回原語,而不是包裝對象,對不對?因爲你將它們與==相比,而不是equals()。

+0

是的,他們是雙打的 – Twinhelix