Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java need equals() if there is hashCode()?

Tags:

java

object

If two objects return same hashCode, doesn't it mean that they are equal? Or we need equals to prevent collisions?

And can I implement equals by comparing hashCodes?

like image 542
Zhambul Avatar asked Mar 16 '17 11:03

Zhambul


People also ask

Why should the equals () and hashCode () methods often be overridden together?

In order to use our own class objects as keys in collections like HashMap, Hashtable etc.. , we should override both methods ( hashCode() and equals() ) by having an awareness on internal working of collection. Otherwise, it leads to wrong results which we are not expected.

What happens if we do not override hashCode () and equals () in HashMap?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

What is the importance of hashCode () and equals () method in Java?

The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.

Can we override hashCode without equals?

Only Override HashCode, Use the default Equals: Only the references to the same object will return true. In other words, those objects you expected to be equal will not be equal by calling the equals method. Only Override Equals, Use the default HashCode: There might be duplicates in the HashMap or HashSet.

Why do we need equals method in Java?

equals() is used to compare the two objects by some business logic and returns a boolean value. Use == operator when you want to compare the values of two primitive data types or you want to compare two references are same or not. Use . equals() method when you want to compare two objects by functionality.

Why we check hashCode () equality before equals () method?

If an object's hashcode is not the same as another object's hashcode, there is no reason to execute the equals() method: you just know the two objects are not the same. On the other hand, if the hashcode is the same, then you must execute the equals() method to determine whether the values and fields are the same.


1 Answers

If two objects have the same hashCode then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function. But the opposite is true - if the objects are equal, then they must have the same hashCode.

like image 83
shmakova Avatar answered Sep 22 '22 05:09

shmakova