How to Override equals() and hashcode() methods in Java?

 

In this tutorial we will see how to Override equals() and hashcode() method in our code. First up all lets see what is equals and hashcode method.
  • equals() method indicates whether other Object is equal to same class Object. It will return boolean value as true when both Objects are equal and false when both Objects are not equals.
  • hashcode() method returns the hashcode of the Object passed and will be called automatically first whenever we use equals() method to compare 2 Objects. 
Lets see java examples for Overriding equals and hashcode method. In this example we will use HashMap to store "MyObject" class instance in key part. 

We all knows that HashMap won't allow duplicate key. In that case first example we will see about storing Object in key without Overriding equals() and hashcode() methods and second example by Overriding equals() and hashcode() methods.

Without overriding equals() and hashcode() methods


class MyObject{

 String val;
 
 public MyObject(String val) {
  this.val = val;
 } 
}




public class MyTest {
 
 public static void main(String[] args) {
  
  MyObject obj1 = new MyObject("sunday"); // 1st 
  MyObject obj2 = new MyObject("monday"); // 2nd 
  MyObject obj3 = new MyObject("sunday"); // 3rd
  
  HashMap<MyObject, String> hm = new HashMap<MyObject, String>();
  hm.put(obj1, "1");
  hm.put(obj2, "2");
  hm.put(obj3, "3");
  hm.put(obj1, "4");
  hm.put(obj1, "5");
  
  System.out.println("HASHMAP SIZE : "+hm.size());
 } 
}


OUTPUT:


HASHMAP SIZE : 3

3 instance we have created and stored in HashMap.


With overriding equals() and hashcode() methods
class MyObject{
 String val;
 public MyObject(String val) {
  this.val = val;
 } 
 
 @Override
 public boolean equals(Object obj) {
  return ((MyObject)obj).val.equals(this.val);
 }
 
 @Override
 public int hashCode() {
  
  /*We will return same hashcode as 0 for 
  all Object since its same class Object
  */
  return 0;
 }
}


OUTPUT:

HASHMAP SIZE : 2


Same MyTest class and MyObject class Overrides equals() and hashcode() methods. In equals method we have compared 2 Objects of "MyObject" class member variable "val" and returned true when 2 objects have same value "sunday". Hence we have only 2 elements in HashMap. 







No comments:
Write comments