Override Equals and Hashcode Method
Override Equals and Hashcode Method
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
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
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);
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.
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