0% found this document useful (0 votes)
93 views

Override Equals and Hashcode Method

The document discusses the need to override the hashCode() and equals() methods in Java. It provides examples of how objects may not be found properly in collections like HashSet without overriding these methods. Specifically, it shows that two objects that are logically equal may not be identified as equal without overriding hashCode() and equals() to check for equality based on object attributes rather than memory location. It also demonstrates that objects cannot be reliably added or searched for in a HashMap by key if these methods are not overridden.

Uploaded by

vaka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Override Equals and Hashcode Method

The document discusses the need to override the hashCode() and equals() methods in Java. It provides examples of how objects may not be found properly in collections like HashSet without overriding these methods. Specifically, it shows that two objects that are logically equal may not be identified as equal without overriding hashCode() and equals() to check for equality based on object attributes rather than memory location. It also demonstrates that objects cannot be reliably added or searched for in a HashMap by key if these methods are not overridden.

Uploaded by

vaka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

http://shivasoft.

in/blog/java/what-is-the-need-to-override-hashcode-andequals-method/
http://www.javaworld.com/community/node/1006
override hashcode and equals method
Case - 1
Emp.java
package com.vbr;
public class Emp {
private int age;
Emp(int age){
this.age=age;
}
public int hashCode(){
return age;
}
}
TestEmp.java
public class TestEmp{
public static void main(String[] args){
Emp emp = new Emp(10);
System.out.println("emp.hashCode()-->>>"+emp.hashCode());
}
}
Output
emp.hashCode()--->>>10
get the original hashcode of an object
public class TestEmp{
public static void main(String[] args){
Emp emp = new Emp(10);
int originalHashCode=System.identityHashCode(emp);
System.out.println("emp.hashCode()-->>>"+emp.hashCode());
System.out.println("Original hashCode of Emp--->>>"+originalHashCode);
}
}
Output
emp.hashCode()--->>>10
Original hashCode of Emp---->>>3541984
If you want to compare two objects based upon the equals() method
you have to override both hashCode() and equals() methods.
Emp.java
1

public class Emp {


private int age;
Emp(int age){
this.age=age;
}
public int hashCode(){
return age;
}
public boolean equals(Object obj){
boolean flag = false;
Emp emp =(Emp)obj;
if(this.age == emp.age)
flag=true;
return flag;
}
}
TestEmp.java
public class TestEmp{
public static void main(String[] args){
Emp emp1 = new Emp(10);
Emp emp2 = new Emp(10);
System.out.println("emp1.equals(emp2)-->>>"+emp1.equals(emp2));
}
}
case - 2
Think of a test scenario where you want to store your objects in a
HashSet and you want to find a particular object. First let us see if
we do not override the methods and we want to store the objects in
the HashSet. Let us analyse the impact of it from the following code.
Emp.java
public class Emp {
private int age;
Emp(int age){
this.age=age;
}
TestEmp.java
import java.util.HashSet;
public class TestEmp{
public static void main(String[] args){
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(24);
Emp emp3 = new Emp(25);
2

Emp emp4 = new Emp(26);


Emp emp5 = new Emp(27);
HashSet<Emp> hs = new HashSet<Emp>();
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
hs.add(emp4);
hs.add(emp5);
System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains(
new
Emp(25))-->>>"+hs.contains(new Emp(25)));
System.out.println("hs.remove(
new
Emp(24)-->>>"+hs.remove( new Emp(24)));
System.out.println("Now HashSet Size--->>>"+hs.size());
}
}
If you run the above program, the will output will be like the following.
HashSet Size--->>>5
hs.contains( new Emp(25))--->>>false
hs.remove( new Emp(24)--->>>false
Now HashSet Size--->>>5
It means that you cannot find the object. However it is not the case
for Integer object. You can put object of type Integer in a HashSet
and you can try and you can see the effect. Now let us modify the
Emp class so that we will get over the problems what we faced in
the above test harness class.
Emp.java
public class Emp {
private int age;
Emp(int age){
this.age=age;
}
public int hashCode(){
return age;
}
public boolean equals(Object obj){
boolean flag = false;
Emp emp =(Emp)obj;
if(this.age == emp.age)
flag=true;
return flag;
}
}
3

TestEmp.java
import java.util.HashSet;
public class TestEmp{
public static void main(String[] args){
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(24);
Emp emp3 = new Emp(25);
Emp emp4 = new Emp(26);
Emp emp5 = new Emp(27);
HashSet<Emp> hs = new HashSet<Emp>();
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
hs.add(emp4);
hs.add(emp5);
System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains( new Emp(25))-->>>"+hs.contains(new Emp(25)));
System.out.println("hs.remove( new Emp(24)-->>>"+hs.remove( new Emp(24)));
System.out.println("Now HashSet Size--->>>"+hs.size());
}
}
Output
HashSet Size--->>>5
hs.contains( new Emp(25))--->>>true
hs.remove( new Emp(24)--->>>true
Now HashSet Size--->>>4
Case 3
In this case you want to use your object as key not the value in the
HashMap. So you have to override both the methods hashCode()
and equals(). However it is left to the reader to create the object
and test the feature in a Map.
Case - 4
If want to make your own immutable object , it will be wiser to
override the equals() and hashCode() methods.
To test the above programs, please create the appropriate package
as mentioned in the program. You can also create your own package
and modify the package name in the above programs. You can all
the code in your favourable java editor.
What is the need to Override Hashcode() and equals() method
Few Thump rules:

If two objects are same then they must return same value in
hashcode() and equals() method whenever invoked.
It is not necessary that two different object must have different
hashcode values. it might be possible that they share common hash
bucket.
JVM assigns unique hashcode value to each object when they are
created in memory and if developers dont override the hashcode
method then there is no way the two object returns same hashcode
value.
As the question comes in your mind that equals() method is used to
compare objects that they are having same value or not but why
should we override the hashcode method ?
The answer to the question is for the hash technique based data
structures like HashMap and Hashtable.

As you can see in above diagram that every object is placed in Hash
bucket depending on the hashcode they have. It is not necessary
that every different object must have different hashcode. hashcode
is used to narrow the search result. When we try to insert any
key in HashMap first it checks whether any other object present with
same hashcode and if yes then it checks for the equals() method. If
two objects are same then HashMap will not add that key instead it
will replace the old value by new one.
What will happen if I dont override the hashcode method?
Ans : If the object does not implement hashcode() method and used as
key then we will not get the object back as shown in below code.
Code without implementation of equals() and hashcode()
HashMapDemo.java
import java.util.HashMap;
class Movie{
5

private String name,actor;


private int releaseYr;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setActor(String actor){
this.actor=actor;
}
public String getActor(){
return actor;
}
public void setReleaseYr(int releaseYr){
this.releaseYr=releaseYr;
}
public int getReleaseYr(){
return releaseYr;
}
}
public class HashMapDemo {
public static void main(String[] args){
Movie m1=new Movie();
m1.setActor("akshay");
m1.setName("Thank You");
m1.setReleaseYr(2011);
Movie m2=new Movie();
m2.setActor("akshay");
m2.setName("Khiladi");
m2.setReleaseYr(1993);
Movie m3=new Movie();
m3.setActor("akshay");
m3.setName("Taskvir");
m3.setReleaseYr(2010);
Movie m4=new Movie();
m4.setActor("akshay");
m4.setName("Taskvir");
m4.setReleaseYr(2010);

HashMap<Movie,String> map= new


HashMap<Movie,String>();
map.put(m1,"ThankYou");
map.put(m2,"Khiladi");
map.put(m3,"Tasvir");
map.put(m4,"Duplicate Tasvir");
//Iterate over HashMap
for(Movie mm:map.keySet()){
System.out.println(map.get(mm).toString());
}

Movie m5=new Movie();


m5.setActor("akshay");
m5.setName("Taskvir");
m5.setReleaseYr(2010);
/*we are trying to retrieve m3, by creating object m5 with
exact values as of m3, However hashcode method is not implemented
and that why we are not able to get object m3*/
if(map.get(m5) == null){
System.out.println("--------------------");
System.out.println("Object not found");
System.out.println("--------------------");
}else{
System.out.println(map.get(m5).toString());
}
}
}
Output
Duplicate Tasvir
Tasvir
Khiladi
ThankYou
-------------------Object not found
-------------------As you can see in above program :
1.
Duplicate objects are added in HashMap as a key (Because we have
not override the hashcode and equals method)

2.

We are not able to get back object from map (Because hashcode is
not implemented)
Same program with equals and hashcode implementation:
import java.util.HashMap;
class Movie{
private String name,actor;
private int releaseYr;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setActor(String actor){
this.actor=actor;
}
public String getActor(){
return actor;
}
public void setReleaseYr(int releaseYr){
this.releaseYr=releaseYr;
}
public int getReleaseYr(){
return releaseYr;
}
//@override
public int hashCode(){
return actor.hashCode() + name.hashCode() + releaseYr;
}
//@override
public boolean equals(Object obj){
Movie m=(Movie)obj;
return m.actor.equals(this.actor) &&
m.name.equals(this.name) && m.releaseYr == this.releaseYr;
}
}
public class HashMapDemo {
public static void main(String[] args){
Movie m1=new Movie();
m1.setActor("akshay");
m1.setName("Thank You");
m1.setReleaseYr(2011);

Movie m2=new Movie();


m2.setActor("akshay");
m2.setName("Khiladi");
m2.setReleaseYr(1993);
Movie m3=new Movie();
m3.setActor("akshay");
m3.setName("Taskvir");
m3.setReleaseYr(2010);
Movie m4=new Movie();
m4.setActor("akshay");
m4.setName("Taskvir");
m4.setReleaseYr(2010);
HashMap<Movie,String> map= new
HashMap<Movie,String>();
map.put(m1,"ThankYou");
map.put(m2,"Khiladi");
map.put(m3,"Tasvir");
map.put(m4,"Duplicate Tasvir");
//Iterate over HashMap
for(Movie mm : map.keySet()){
System.out.println(map.get(mm).toString());
}

Movie m5=new Movie();


m5.setActor("akshay");
m5.setName("Taskvir");
m5.setReleaseYr(2010);
/*we are trying to retrieve m3, by creating object m5 with
exact values as of m3,
However hashcode method is not implemented and that why
we are not able to get object m3*/
if(map.get(m5) == null){
System.out.println("--------------------");
System.out.println("Object not found");
System.out.println("--------------------");
}else{
System.out.println("---------------------");
9

System.out.println(map.get(m5).toString());
System.out.println("----------------------");
}
}
}
Output
Duplicate Tasvir
Khiladi
ThankYou
--------------------Duplicate Tasvir
---------------------As you can see :
Duplicate Keys are not added instead there values are replaced.
Now the object is retrieved from the Map.
Ques : How to iterate over keyset of HashMap in JDK 4 and 5?
Ans : This is the common question asked in interview.
In JAVA 5 : We can use advance for loop as shown in above code, use
map.keySet(). This will return the Set (As Keys must be unique).
In JAVA 4 : Use map.keySet() and get the Iterator object using
map.iterate() . Then using while loop , get the value for each key.

why do we need to override hashcode and equals method?


if two objects are same then they must return same value in hashcode()
and equals() method whenever invoked.
it is not necessary that two different objects must have different hashcode
values. it might be possible that they share common hash bucket.
jvm assigns unique hashcode value to each object when they are created
in memory and if developers donot override the hashcode method then
there is no way the two objects returns same hashcode value.
what happens if you don't override hashcode?
example: hashset allows duplicate item insertion if hashcode is not
overridden.
if the object doesnot implement hashcode() method and used as key then
we will not get the object back from collection.

whenever we are calling hs.contains(new emp(25)) or map.get(new


emp(25)) then immediately it will calculate the hashcode. that means it
calls the hashcode() method and returns the hashcode. based on
10

hashcode it will goes to the particular hash bucket after going to the
particular bucket it will call the equals() method to find the content of
object.
what happens if you don't override hashcode?
i tell you its very dangerous if you don't override hashcode.
if the object is key and within object if you are not override hashcode()
method then its very dangerous to maintain.
hashset allows duplicate items insertion if hashcode() method is not
overridden.

11

You might also like