override equals() and hashcode() in hashset

Why override equals() and hashcode() in hashset

Ans:- By nature HashSet has unique element. When any new element is added in HashSet, HashSet check uniqueness of new element through the equals() and hashcode() method. 

By Default equals() method code in Object class is

public boolean equals(Object obj) {
return (this == obj);
}

So through this code, two object can equal only if they refer to the same object.
Same as , if equals() method for two object return true then hashcode() method also return same code.

This is failure if two std object with same Student name .
For Example :
Student std1 = new Student ();
std1.setLegalName("raju");

Student std2 = new Student ();
std2.setLegalName("raju");

Both the objects are same but based on the default above method both objects are dirrefent because references and hashcode are different .

So You will found duplicate variable in HashSet.
For resolve this problem, HashSet override this method.

public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student))
return false;
Student std = (Student)o;
return std.legalName == legalName
}

public int hashCode(){
return Math.random();

}
}

Comments

  1. Nice article but I believe its important to understand the consequences of not following this contract as well and for that its important to understand application of hashcode in collection classes e.g. How HashMap works in Java and how hashcode() of key is used to insert and retrieve object from hashMap.

    Javin

    ReplyDelete

Post a Comment

Recent Post

Recent Posts Widget

Popular posts from this blog

Capture image from webcam java code, examples

How to capture finger prints in java

Shallow Copy Deep Copy Java example