Couple of questions and explanation is required for hashcode and equals method in hashcode. Below are the questions :
- when does the hashcode and equals gets called during put or get ?
- When we are storing custom object, then i found in every tutorials that we need to override hashcode. But if I donot override either, then it produces the same result. Except when I use new operator . Below is sample program :
I am storing employee objects into the hashmap and then i didnot override hashcode and equals method, then the code works as expected.
Employee e1= new Employee("ram", 1000);
Employee e2= new Employee("sai", 1001);
Employee e3= new Employee("krishna", 1002);
System.out.println("e1.hashCode() : "+e1.hashCode());
System.out.println("e2.hashCode() : "+e2.hashCode());
System.out.println("e3.hashCode() : "+e3.hashCode());
Map<Employee, String> map= new HashMap<Employee, String>();
map.put(e1, "employee1");
map.put(e2, "employee2");
map.put(e3, "employee3");
for (Entry<Employee, String> entry : map.entrySet())
{
System.out.println(entry.getKey().getName() +"-"+entry.getKey().getid() + "-" + entry.getValue());
}
System.out.println(map.get(e3));
System.out.println(map.get(new Employee("krishna", 1002)));
- When you override equals, what things need to be taken care.
- When you override hashcode , what things need to be taken care.
- When you override only equals, then the how the default hashcode will behave.
- When you override only hashcode, then how the default equals will behave.*