Scenario:
I have one class Employee That have some filed and Employee also implemented Hash code and equals method
Case 1: Hashcode () was implemented such that it always return some random no for every object.
Like for same object also returning different hascode
Case2: Hashcode () was implemented such way it return same hashcode for all object may me they object are same or different.
What is the output of following program?
public class HascodeTest {
public String name;
public static void main(String[] args) {
HashMap test=new HashMap();
HascodeTest ht=new HascodeTest("test");
test.put(ht,"hello");
test.put(ht,"hello");
test.put(ht,"hello");
test.put(ht,"hello");
test.put(ht,"hello");
System.out.println("HashmapSize"+test.size());
System.out.println(ht);
}
public HascodeTest(String name) {
super();
this.name = name;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
//return true;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
int hashcode=super.hashCode();
System.out.println("HashCode:"+hashcode);
int renVal=(int) (31 * Math.random());
System.out.println("HashCode"+renVal);
return renVal;
//return 3 in case 1;
}
@Override
public String toString() {
System.out.println("Calling to String ");
return this.name;
}
}
Ans:
Case 1 :Size of hashmap is 4
Case2:size of hashmap is 1
First it checks if hashode are same then only he goes for equity check and key are equal or not
i.e if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
i.e if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
So if hashocode are different then it has not check equals.
So implementation of correct hashcode is very important
No comments:
Post a Comment