Wechat search “Java fish”, a knowledge point every day not bad

(1) One knowledge point every day

If two objects have the same hashCode(), must equals() also be true?

(2) Conclusions

This is a very common and very simple interview question.

HashCode () is the same for both objects, and equals() is not set to true;

Hashcode of two objects must be true if equals is true;

(3) Learn a little more

First, let’s look at what the hashCode() method does. HashCode exists mainly for quick lookups, such as the commonly used HashMap collection. HashCode is used to determine the storage address of an object in the hash storage structure.

All objects in Java have a parent class Object, and Object has a hashCode method, and all classes in Java have hashCode methods.

Let’s look at how hashCode is computed:

for (Object element : a)
    result = 31 * result + (element == null ? 0 : element.hashCode());
Copy the code

Hashcode is the result of a single operation on each element of an object. It is possible for two different objects to have the same hash value.

For example, the following two strings:

String s1="Ma";
String s2="NB";
System.out.println(s1.hashCode()==s2.hashCode());  //true
System.out.println(s1.equals(s2));  //false
Copy the code

Although the Ma and NB strings are different, they have the same hashcode value of 2484.

< span style = “color: RGB (51, 51, 51); font-size: 14px! Important; white-space: inherit! Important;”

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null|| getClass() ! = o.getClass())return false;
    User user = (User) o;
    return Objects.equals(name, user.name) &&
            Objects.equals(age, user.age);
}

@Override
public int hashCode(a) {
    return Objects.hash(name, age);
}
Copy the code

Similarly, entity objects can have two different objects with the same hash value.