The original address: https://www.jianshu.com/p/3819388ff2f4
Overriding hashCode() is a common question that comes up in job interviews. After reading this article, you must have a better understanding of the problem. The equals and hashCode methods are both methods of the Object class.
public boolean equals(Object obj) {
return (this == obj);
}
Copy the code
public native int hashCode();
Copy the code
The equals method calls “==” internally, so it compares whether two objects have the same reference to the same memory address without overriding the equals method.
HashCode is a local method that returns the memory address of the object.
So with that in mind, let’s move on.
General rules for hashCode:
The hashCode method must always return the same value for multiple calls to the same object during the execution of the application, as long as the information used for the equals method comparison of the object has not been modified. The value returned by executing the hashCode method can be inconsistent between one application and another.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on both objects must produce the same integer result
If two objects are not equal according to equals(Object), then calling the hashCode method on those two objects does not necessarily require that the hashCode method produce a different result. But programmers should be aware that it is possible to improve hash table performance by producing radically different integer results for unequal objects.
Overwriting equals without overwriting hashCode violates rule 2. Equal objects must have equal Hash codes.
Next, I’ll use a program to demonstrate the serious consequences of not overwriting the hashCode method:
public class Test {
public static void main(String[] args) {
Person person1 = new Person("TUCJVXCB");
Person person2 = new Person("TUCJVXCB");
Map<Person, Integer> hashMap = new HashMap<>();
hashMap.put(person1, 1);
System.out.println(person1.equals(person2));
System.out.println(hashMap.containsKey(person2));
}
static class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Person) {
Person person = (Person) obj;
return name.equals(person.name);
}
return false; }}}Copy the code
Here are the input results
true
false
Copy the code
The first output true is easy to know because we overrode equals to return true as long as the names of two objects are the same. But why is the second why is the output false? Because we didn’t override the hashCode method. So we conclude that if a class overrides equals but not hashCode, it will not work with all hash-based collections (HashMap, HashSet).
So how do we solve this problem, it’s very simple, just rewrite the hashCode method.
@Override
public int hashCode() {
return name.hashCode();
}
Copy the code
After modification, enter the following:
true
true
Copy the code