Search This Blog

Monday 24 October 2016

hashCode and equals contract in java

public boolean equals(Object obj),public int hashCode() are methods of Object class.


Equals Demo Without Hashcode:
-----------------------------
import java.util.HashMap;

public class Emp{
private String name;

public Emp(String _name) {
name = _name;
}

public boolean equals(Object obj) {
if(obj==null) return false;
if (!(obj instanceof Emp))
return false;
if (obj == this)
return true;
return this.name.equals(((Emp) obj).name);
}
}

public class EqualsDemoWithoutHashcode {

public static void main(String[] args) {
Emp emp1 = new Emp("XYZ");
Emp emp2 = new Emp("ABC");

//HashMap stores Emp type and its salary
HashMap<Emp, Integer> m = new HashMap<Emp, Integer>();
m.put(emp1, 1000);
m.put(emp2, 20000);
System.out.println(m.get(new Emp("XYZ")));
}
}

In this case emp1 and emp2 hashcodes are different and equals also returned false as data different of the objects. And emp1 and emp2 are placed into hashmap. Here Object class hashcode function will be used to generate hash code. So while retrieving object from hashmap again it uses Object class hashcode function and it will not give any surety for user defined class objects to create same hash code for the object while retrieving. So if hash code is not same then it gives inconsistent data.


Similarly Suppose implemented hash code function and equals method not implemented. It will stores duplicate keys because it uses Object class equals method and it will not compare data of the object but it compares references. So references are not same so it stores duplicate keys.


HashMap stores internally data in table format and it uses hashcode function and equals method. To store objects in hashmap first it generates hash code and based on the hash code it stores in the bucket. Suppose same hash code is generated for two key objects then it uses equals method whether both key objects are same or different. If two key objects are different then it maintains multiple objects in the same bucket with same hash code.

No comments:

Post a Comment