Explanations online are very comprehensive but dry and difficult to understand. In essence, this requirement exists to ensure the retrieval efficiency of hash tables when an object is used as a key. For example, the get method of HashMap obtains the corresponding value in two steps:
- First step: find the corresponding hash bucket via the hash value of the key
- Second step: use the equals method to determine if it is the same key (because hash collisions can occur)
Suppose a Student class has three attributes: student ID, name, and age. We define that two Student objects represent the same student as long as their student IDs are the same. In this case, we override the equals method:
public class Student { private String idCard; private String name; private String age;@Override public boolean equals(Object obj) { if (obj instanceof Student) { if (this.idCard.equals(((Student) obj).idCard)) { return true; } } return false; }
}
If we do not override the hashCode method, when retrieving from a Map using a Student object as the key, if two Student objects have the same student ID but different names and ages, their hashCode will most likely be different. Therefore, in the first step of retrieval via the get method, the object cannot be found using the hashCode, so the get call will return null. However, by our definition, students with the same ID are the same object, and we expect to find that object. This contradicts our original intention.
Therefore, it is established by convention that if you override the equals method, you must also override the hashCode method; this is called "convention consistency".
public class Student { private String idCard; private String name; private String age;@Override public boolean equals(Object obj) { if (obj instanceof Student) { if (this.idCard.equals(((Student) obj).idCard)) { return true; } } return false; } @Override public int hashCode() { return this.idCard.hashCode(); }
}
With this implementation, the first step of the get method can find the object via the same hashCode, and the equals method can then confirm that it is the same object.
This discussion topic was separated from the original post at https://juejin.cn/post/7368823201068695602