2015-10-05 55 views
0

我是計算機工程專業的學生,​​我已經在一週前開始Java。我一直在研究這些天泛型類型,我想與equals和Overriding混合使用,所以我編寫了一個程序,它創建了一個名爲「Punto」的對象,它具有兩個屬性(pointX,pointY),以便模擬座標。我在主類之外編寫了一個靜態方法,它使用兩個「Puntos」作爲參數並等於它們。下面是該方法的代碼:改寫等於方法給出錯誤

public static boolean iguales(PuntoImpl<Double> p1, PuntoImpl<Double> p2){ 
    return p1.equals(p2); 
} 

這是我的首要的嘗試等於:

@Override 
public boolean equals(final Object obj) 
{ 
    if (obj == null || !(obj instanceof PuntoImpl)) 
     return false; 

    PuntoImpl<T> other = (PuntoImpl<T>) obj; 

    if (other.puntoX != this.puntoX)  return false; 
    if (other.puntoY != this.puntoY)  return false; 

    return true; 
} 

我試圖與協調X和座標Y相同的參數等於兩分,但它返回我是假的。你能幫我找到錯誤嗎?

+0

putoX和putoY有哪些類型? – Stultuske

+0

instanceof已經做了一個空檢查,如果你這樣做,你可以保留nullcheck,但是我會建議通過檢查實際類的相等性來替換instanceof檢查。 – Stultuske

+0

他們是T類型(通用),但我使用他們作爲雙 – xFunkyTImes

回答

4

您正在比較Double值的參考平等。我懷疑你想if (!other.puntoX.equals(this.puntoX))等。其實我寫這個代碼:

@Override 
public boolean equals(final Object obj) 
{ 
    if (obj == null || obj.getClass() != getClass()) { 
     return false; 
    } 
    if (obj == this) { 
     return true; 
    } 

    PuntoImpl<T> other = (PuntoImpl<T>) obj; 

    return other.puntoX.equals(this.puntoX) && 
      other.puntoY.equals(this.puntoY); 
} 

不要忘了覆蓋hashCode爲好。

另請注意,比較精確相等的浮點值通常會給出意想不到的結果。您可能想要提供一種查找點之間距離的方法,而不是覆蓋equals,因此您可以將它們與某個容差進行比較。

+0

不應該如果(obj == this)返回true? –

+0

@RaviThapliyal:對不起,是的 - C&P失敗。 –

+0

@JonSkeet現在終於開始了!非常感謝你的回答,這很容易理解:) – xFunkyTImes