私は本から読みましたが、Objectクラスのequals()
メソッドをオーバーライドしている限り、そのhashCode()
メソッドもオーバーライドする必要がありますが、なぜhashCode()
メソッドをオーバーライドする必要があるのかわかりません。hashCode()とequals()オーバーライドが実際にどのように機能しますか?
public class Employee {
public int employeeId;
public String firstName, lastName;
public int yearStarted;
Employee(){}
Employee(int employeeID){
this.employeeId = employeeID;
}
// @Override
// public int hashCode() {
// return employeeId;
// }
public boolean equals(Object e) {
if(!(e instanceof Employee)){
return false;
}
else {
Employee newEmp = (Employee)e;
return this.employeeId == newEmp.employeeId;
}
}
public static void main(String[] args) {
Employee one = new Employee(101);
if (one.equals(new Employee(101)))
System.out.println("Success");
else
System.out.println("Failure");
}
}
そして、私は「成功を」取得結果を、私はequals()
はなく、hashCode()
を上書きしながら実行している:のは、以下の次の例を考えてみましょう。したがって、equals()
メソッドをオーバーライドするときにhashCode()
に関連するプロセスフローが実際にどのように見えるのですか。その場合、hashCode()
とequals()
の両方をオーバーライドする必要がありますか?ありがとうございました!