What are equals and hashCode method do?
Equals and hashCode in Java are two fundamental method which is declared in Object class and part or core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object.
But think about scenario I have a Student class.
I am creating two objects of student.
Now look at the output
Wheteher roll numbers ,fname ,lname are same for both objects output is false.
whenever we use == operator for object or equals to method for object. java check whether two reference pointing same memory location or not. if they are not pointing same memory, java consider it as two different objects.
In this scenario HashSet also add s1 and s2. But it is wrong according to user view.
Here we need to change default behaviour of java equals method.
So we need to override the equals method of object class and custmize it to our requirement.
I am adding two method in my Student class.
We are adding hashCode method also,because equals object must have same hash code.
Now run the application and look at the output :
It is common practise that whenever we want to add Class object to HashSet, TreeSet,ArrayList, or any java collection we override equals() and hashCode method.
Next ...
In my next post I will explain functionality of TreeSet.
Hope it will help full.
No comments:
Post a Comment