我創建了一個包含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;
}
}
請幫助我。提前致謝!
你的問題是什麼? – Andrew
問題是什麼?你沒有問任何問題。我建議閱讀下面的線程,並再次詢問是否遇到問題:請參閱[這裏](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