1600 PMP mock questions 1400 CAPM mock questions 800 SCJP 6 mock questions 600 OCAJP 7 mock questions 590 OCPJP 7 mock questions 556 SCWCD 5 mock questions 500 OCEJWCD 6 mock questions pdfDownload (java,struts, hibernet etc)

Java Tutorials

Why override equals() and hashCode()?

If you are implementing HashSet to store unique object then you need to implement equals() and hashcode() method.
if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).
Two scenarios
Case 1) : If you don?t implement equals() and hashcode() method :
When you are adding objects to HashSet , HashSet checks for uniqueness using
equals() and hashcode() method the class ( ex. Emp class). If there is no equals() and hashcode() method the Emp class then HashSet checks default Object class?s
equals() and hashcode() method.
In the Object class , equals method is
public boolean equals(Object obj) {
    return (this == obj);
Under this default implementation, two references are equal only if they refer to the exact same object. Similarly, the default implementation of hashCode() provided by Object is derived by mapping the memory address of the object to an integer value.
This will fail to check if two Emp object with same employee name .
For Example :
Emp emp1 = new Emp();
Emp emp2 = new Emp();
Both the objects are same but based on the default above method both objects are dirrefent because references and hashcode are different .
So in the HashSet you can find the duplicate emp objects.
To overcome the issue equals() and hashcode() method need to override.
Case 2) : If you override equals() and hashcode() method
Example : implement equals and hashcode
public class Emp {
    private long empId;
    String name = "";
public boolean equals(Object o) {
        if (o == this)
        return true;
        if (!(o instanceof Emp))
        return false;
        Emp emp = (Emp)o;
        return emp. empId == empId &&
        emp. name == name;
    public int hashCode(){
        int result = 10;
        result = result * new Integer(String.valueOf(empId)).intValue();
        return result;
In the equals() , it check for name is same or not. This way you can find out the objects are equals or not.
In the hashCode() also it return some unique value for each object. In this way if two Emp object has same empId then it will say both are same object.
Now HashSet store only unique objects.
If you do
Emp emp1 = new Emp();
Emp emp2 = new Emp();

This will print : equal

Reviews and Comments

PMP, CAPM, PMI is a registered certification mark of the Project Management Institute, Inc

Copyright © www.techfaq360.com 2016

About US | Contact US | Privacy Policy | Terms and Conditions  | Website disclaimer  | Cancellation and Refund Policy  | Shipping & Delivery Policy