Posts

Showing posts from October 13, 2010

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…

Recent Post

Recent Posts Widget