2016-06-26 46 views
0

我創建了一個包含2個字段的類。一個Double和一個Line2D。我要重寫equals方法,使下面的代碼返回真重寫哈希碼並等於自定義類

public class Main { 

    public static void main(String[] args) { 
     StatusLinePair slp1 = new StatusLinePair(25.0, new Line2D.Double(123.0, 32.0, 342.0, 54.0)); 
     StatusLinePair slp2 = new StatusLinePair(25.0, new Line2D.Double(123.0, 32.0, 342.0, 54.0)); 

     System.out.println(slp1.equals(slp2)); 
    } 

} 

這是我做過嘗試,但我仍然沒有得到預期的效果

public class StatusLinePair { 
    public Double yAxisOrder; 
    public Line2D line; 

    public StatusLinePair(Double yAxisOrder, Line2D line) { 
     this.yAxisOrder = yAxisOrder; 
     this.line = line; 
    } 

    @Override 
    public int hashCode() { 
     final int prime = 31; 
     int result = 1; 
     result = prime * result + ((line == null) ? 0 : line.hashCode()); 
     result = prime * result + ((yAxisOrder == null) ? 0 : yAxisOrder.hashCode()); 
     return result; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     StatusLinePair other = (StatusLinePair) obj; 

     if (this.yAxisOrder == other.yAxisOrder && this.line.getX1() == other.line.getX1() 
       && this.line.getX2() == other.line.getX2() && this.line.getY1() == other.line.getY1() 
       && this.line.getY2() == other.line.getY2()) 
      return true;   

     return false; 
    } 
} 

請幫助我。提前致謝!

+0

你的問題是什麼? – Andrew

+0

問題是什麼?你沒有問任何問題。我建議閱讀下面的線程,並再次詢問是否遇到問題:請參閱[這裏](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and- hashcode-methods-in-java)和[here](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java )。 – RK1

回答

1

您沒有使用Line2D.equals,所以我認爲這沒有按照您需要的方式實現,或者您會使用它。如果是這種情況,則不應該使用Line2D.hashCode()。

總之,要麼使用Line2D.hashCode()和Line2D.equals(),要麼不使用混合。

2

有幾個問題與您的代碼:

  • 它應該返回false如果其他對象不是StatusLinePair,而不是拋出一個ClassCastException
  • 它應該返回false如果其他對象爲空,而不是拋出一個空指針異常
  • 它不應該比較Double實例與==,但與equals()(或該類應該包含一個雙精度,而不是一個雙精度,因爲它似乎不可爲空):這是您的原因具體問題。
  • 它不應該使用Line2D.hashCode(),因爲它不使用Line2D.equals()
1

使用==你是不是比較對象,但refrence的實際值。

For example: 
    Object a = new Object(); 
    Object b = a;    // if you compare these two objects with == it will return true 

But 
    Object a =new Object(); 
    Object b = new Object(); // if you compare these two objects with == then it will return false as they are pointing to two different objects 

通過覆蓋equals()方法你可以根據自己的價值觀比較兩個對象。 check this link out for more on equals

我希望這是有幫助的。三江源