2014-04-04 106 views
0

我發現一個方法等於比較兩個移動,我想簡化它。簡化Java布爾比較

public boolean equals(Object obj) { 
    if (obj == null) { 
     return false; 
    } 
    if (getClass() != obj.getClass()) { 
     return false; 
    } 
    final Move other = (Move) obj; 
    return !(this.initialBalls != other.initialBalls && 
      (this.initialBalls == null || !this.initialBalls.equals(other.initialBalls))) 
      && this.direction == other.direction && this.color == other.color; 
} 

有人有想法嗎?

+3

也許代碼審查的人可以幫助你:http://codereview.stackexchange.com/ –

+1

那return語句是不必要的複雜性。前往CR,我會很樂意提供更簡單的東西。 –

+1

這個問題似乎是脫離主題,因爲它是關於codereview,因此屬於該網站。 –

回答

0

您可以使用Apache Commons的EqualsBuilder

public boolean equals(Object obj) { 
    if (obj == null) { return false; } 
    if (obj == this) { return true; } 
    if (obj.getClass() != getClass()) { 
     return false; 
    } 
    Move rhs = (Move) obj; 
    return new EqualsBuilder() 
     .appendSuper(super.equals(obj)) 
     .append(initialBalls, rhs.initialBalls) 
     .append(direction, rhs.direction) 
     .append(color, rhs.color) 
     .isEquals(); 
    } 
+2

爲什麼額外的依賴只是爲了那個? – async

+1

爲什麼不呢?在OP中是否存在一個限制,即沒有第三方庫被允許?當你正在比較的字段是浮點數值時,你是否知道實現'equals()'的正確方法?你相信所有與你一起工作的開發者也一樣嗎?如果你的字段不是原語,它還會節省大量的空檢查。 –

+0

紅鯡魚多嗎?您仍然無法證明只需在正確的位置添加幾個空格/新行或通過移動幾個字符即可完全使用完整的庫來完成您自己的任務。我一般不會講,但是關於OP的任務,這絕對是微不足道的。 – async