I am trying to understand hashcode()
. I have 2 scenarios
1) implementing hashmap
with employee2 class objects
2) implementing hashMap
with primitives(though they are not primitives)
In case of class objects i understand that if i don't implement hashcode()
it generates a random hashcode() every time , so when i retrieve the object , it looks into some different bucket each time and return NULL
But why dosen't this happen in the 2nd case when i don't use class objects
code is as follows:
package programs;
import java.util.*;
public class employee2
{
private int empid;
private String name;
private String dept;
public employee2(int empid,String name,String dept){
this.empid=empid;
this.name=name;
this.dept=dept;
}
int getEmpid(){
return this.empid;
}
@Override public boolean equals(Object o){
employee2 e=(employee2)o;
return getEmpid()==e.empid;
}
@Override public int hashCode() {
int hash = 7;
hash = 83 * hash + this.empid;
return hash;
}
@Override public String toString(){
return empid+", "+name;
}
public static void main(String args[]){
//HashMap with employee class objects
Map<employee2,String> emap=new HashMap<>();
emap.put(new employee2(98446,"Amol Singh","Science"),"good");
emap.put(new employee2(98446,"Robin Singh","Math"),"very good");
// I get null if i dont override hashcode()
System.out.println(emap.get(new employee2(98446,"Robin Singh","Math")));
// New HashMap without Class objects
Map<Integer,String> emap2=new HashMap<>();
emap2.put(23,"amol");
emap2.put(2,"Robin");
// I get correct answer without overriding hashcode()
System.out.println(emap2.get(23));
}
}