I have created a Employee class with 3 parameters.
- Id
- Name
- Age
Requirement: Search based on Name. This is a case where all employees have a unique name. Its mandatory to add the objects with key as id. There are rare cases where it is required to search based on name.
What i have done :
Within the class I am overriding hashCode and Equals method.
I am adding a list of these objects into the hashmap with id as key and value as Employee object
But while adding or searching from a hashmap both the methods do not get called
So what is the use of these methods in terms on hasmap?
Employee Class
public class Employee { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int hashCode() { return name.hashCode(); } public boolean equals(Employee emp) { if (emp == null) return false; else if (emp.name.equalsIgnoreCase(this.name)) return true; else return false; } } Main Method:
public class HashMapTest { public static void main(String[] args) { Employee emp1=new Employee(); emp1.setId(1); emp1.setName("Maclean"); emp1.setAge(24); Employee emp2=new Employee(); emp2.setId(2); emp2.setName("Sampath"); emp2.setAge(25); Employee emp3=new Employee(); emp3.setId(3); emp3.setName("Achar"); emp3.setAge(27); Employee emp4=new Employee(); emp4.setId(4); emp4.setName("Sudheer"); emp4.setAge(25); Employee emp5=new Employee(); emp5.setId(5); emp5.setName("Kunder"); emp5.setAge(25); HashMap<Integer, Employee> empmap=new HashMap(); empmap.put(emp1.getId(), emp1); empmap.put(emp2.getId(), emp2); empmap.put(emp3.getId(), emp3); empmap.put(emp4.getId(), emp4); empmap.put(emp5.getId(), emp5); Employee emp=new Employee(); emp.setName("Maclean"); System.out.println(empmap.containsValue(emp)); System.exit(1); } } Update Solution:
Thanks for all the answers.
1. hashCode method gets called only if the Key is a object and the method exists within the Key Class
2. Equals(Employee emp) is causing function overloading instead of overriding. I should have used equals(Object o)
Changes in the code to resolve the issue
@Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Employee)) return false; Employee emp = (Employee) o; if (emp.name.equalsIgnoreCase(this.name)) return true; else return false; }
idis the unique attribute, shouldn'thashCodebe based on that instead of name? Also, thehashCodemethod is called on the object that is the key to the map, i.e. the id, not the value, i.e. the Employee.