.equals
方法有些困惑。例如:
Test test1 = new Test(3);
Test test2 = new Test(3);
//The if comparison does the same thing that the overridden `.equals()` method does.
if(test1.equals(test2)){
System.out.println("test1 and test2 are true in .equals()");
}
// Override .equals method.
public boolean equals(Object object) {
if(object instanceof Test && ((Test)object).getValue() == this.t) {
return true;
} else {
return false;
}
}
我不明白为什么我们需要重写.equals()
方法。
test1.equals(test2)
,它将无法按照您的预期工作。 - Bhesh Gurungequals()
方法,就必须同时重写hashCode()
方法。 - exexzian