public class DemoHashSet {
private String name;
private String dob;
private String gender;
public DemoHashSet(String name, String dob, String gender) {
super();
this.name = name;
this.dob = dob;
this.gender = gender;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public String getGender() {
return gender;
}
@Override
public String toString() {
return name+" "+dob+" "+gender;
}
@Override
public boolean equals(Object o) {
return this.name.equals(((DemoHashSet)o).getName());
}
@Override
public int hashCode() {
int code = this.name.hashCode() + this.dob.hashCode() + gender.hashCode();
System.out.println("Hash Code: "+code);
return code;
}
public static void main(String args[]) throws ParseException {
Map<DemoHashSet, String> hmap = new HashMap<DemoHashSet, String>();
DemoHashSet obj1 = new DemoHashSet("key1", "121990", "male");
DemoHashSet obj2 = new DemoHashSet("key2", "122990", "male");
DemoHashSet obj3 = new DemoHashSet("key3", "123990", "male");
DemoHashSet obj4 = new DemoHashSet("key4", "124990", "male");
DemoHashSet obj5 = new DemoHashSet("key5", "125990", "male");
hmap.put(obj1, "value1");
hmap.put(obj2, "value2");
hmap.put(obj3, "value3");
hmap.put(obj4, "value4");
hmap.put(obj5, "value5");
System.out.println("Get values: ");
System.out.println(hmap.get(new DemoHashSet("key1", "121990", "male")));
System.out.println(hmap.get(new DemoHashSet("key2", "122990", "male")));
}
}
In this code I am overriding hashcode() and equals() function
when I run this code i get following output:
Hash Code: 1457153183
Hash Code: 1457182975
Hash Code: 1457212767
Hash Code: 1457242559
Hash Code: 1457272351
Get values:
Hash Code: 1457153183
value1
Hash Code: 1457182975
value2
when I override only hashCode() function and comment equlas() method I get following output:
Hash Code: 1457153183
Hash Code: 1457182975
Hash Code: 1457212767
Hash Code: 1457242559
Hash Code: 1457272351
Get values:
Hash Code: 1457153183
null
Hash Code: 1457182975
null
Need explanation for this behaviour as the hash code computed in both scenarios is same but it gives null in 2nd case.