What is the real meaning of overriding hashcode and equals methods in Java

What is the real meaning of overriding hashcode and equals methods in Java

What is the real meaning of overriding hashcode and equals methods in Java ?

In many places we would have overridden hashcode and equals method without understanding deeply about it.
Today after reading this post you will come to know,

  •  Why we want to override hashcode and equals ?
  •  What will happen if we override and if we won’t override ?
  • where exactly we need to override the hashcode and equals methods ?Before going further, just understand these few terms,
    POJO: Plain Old Java Objects, we are going to override few fields in the below POJO class [TestVO].

    Set: Set is a type of collection which will not allow the duplicates. It is allowing the TestVO type duplicates. [We did not override the hashcode and equals methods still in the fields of TestVO POJO class].

    Eg:
    Set<String> myStringSet = new HashSet<String>();
    myStringSet.add(“ngdeveloper.com”);
    myStringSet.add(“ngdeveloper.com”);
    for (String setStr : myStringSet) {
    System.out.println(setStr);
    }

    If you execute the above snippet, you will get the “ngdeveloper.com” only once in the console, since it is given as duplicates, it is removed one string.

    Same time if you execute this snippet, we are getting the duplicates,

    TestVO.java

package in.javadomain;

public class TestVO {

private String couponTitle;
private String couponCode;
private String couponShop;

public String getCouponTitle() {
return couponTitle;
}

public void setCouponTitle(String couponTitle) {
this.couponTitle = couponTitle;
}

public String getCouponCode() {
return couponCode;
}

public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}

public String getCouponShop() {
return couponShop;
}

public void setCouponShop(String couponShop) {
this.couponShop = couponShop;
}

}

EqualsHashCodeExample.java

package in.javadomain;

import java.util.HashSet;
import java.util.Set;

public class EqualsHashCodeExample {
public static void main(String[] args) {
Set&amp;amp;lt;TestVO&amp;amp;gt; couponSet = new HashSet&amp;amp;lt;TestVO&amp;amp;gt;();

TestVO testVO1 = new TestVO();
testVO1.setCouponTitle("50% offer for mobiles");
testVO1.setCouponCode("SAVE50");
testVO1.setCouponShop("www.paytm.com");

TestVO testVO2 = new TestVO();
testVO2.setCouponTitle("20% offer for electronics");
testVO2.setCouponCode("SAVE20");
testVO2.setCouponShop("www.flipkart.com");

TestVO testVO3 = new TestVO();
testVO3.setCouponTitle("50% offer for mobiles");
testVO3.setCouponCode("SAVE50");
testVO3.setCouponShop("www.paytm.com");

couponSet.add(testVO1);
couponSet.add(testVO2);
couponSet.add(testVO3);
for (TestVO testVO : couponSet) {
System.out.println(testVO.getCouponTitle());
System.out.println(testVO.getCouponCode());
System.out.println(testVO.getCouponShop());
System.out.println("---------Javadomain.in--------------");
}
}
}

Output:


50% offer for mobiles
SAVE50
www.paytm.com
---------Javadomain.in--------------
20% offer for electronics
SAVE20
www.flipkart.com
---------Javadomain.in--------------
50% offer for mobiles
SAVE50
www.paytm.com
---------Javadomain.in--------------

We got duplicates from Set, so Set allowed the duplicates. No. Set is stored with TestVO, which did not implement any override and hashcode methods for any fields, so Set could not even identify the duplicates so it is printed the way we have inserted.

Ok. In this case how to avoid duplicates in Set ?

Let’s try with overriding equals() and hashcode() methods in TestVO class for couponcode and couponshopfields, then one duplicate should be removed is the expection. Let’s check now.

Don’t you know how to generate hashcode() and equals () method in eclipse ?

Open TestVO -> Right click -> Source -> Generate hashCode() and equals().. -> select only couponcode andcouponshop then click ok.

Now the below part is generated in TestVO.java file,

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((couponCode == null) ? 0 : couponCode.hashCode());
result = prime * result + ((couponShop == null) ? 0 : couponShop.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestVO other = (TestVO) obj;
if (couponCode == null) {
if (other.couponCode != null)
return false;
} else if (!couponCode.equals(other.couponCode))
return false;
if (couponShop == null) {
if (other.couponShop != null)
return false;
} else if (!couponShop.equals(other.couponShop))
return false;
return true;
}

Now will run the EqualsHashCodeExample.java file again,

We got the expected output:

50% offer for mobiles
SAVE50
www.paytm.com
---------Javadomain.in--------------
20% offer for electronics
SAVE20
www.flipkart.com
---------Javadomain.in--------------

Hope you got the clear understandings about overriding hashCode() and equals() methods in Java.

 

758 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *