Using HashSet with a user class Employee
equals, hashcode, hashset, java, set
Solution
You're overloading `equals` rather than overriding it. Its parameter should be of type `Object`.
But also your `hashCode` is checking the `id` while `equals` is checking the `name`. They should probably be constructed from the same properties.
Problem
I know this will sound a very dumb question, but I got confused after what I have known about `HashSet` and what I see when I execute below code. I have an Employee class as follows (keeping only relevant piece of code): ``` public class Employee { //assume it has 3 variable name(String),salary(double) and id(int) //assume the constructor, getter-setters are there //following is my equals and hashCode implementation public boolean equals(Employee e){ return name.equals(e.name); } public int hashCode(){ return id; } } ``` Now I have following code which uses `HashSet` : ``` Employee e1 = new Employee("Abc", 2.0, 1); Employee e2 = new Employee("abc", 3.0, 4); Employee e3 = new Employee("XYZ", 4.0, 3); Employee e4 = new Employee("Mno", 5.0, 2); Employee e5 = new Employee("Abc", 77.0, 1); Set<Employee> sEmp = new HashSet<Employee>(); sEmp.add(e1); sEmp.add(e2); sEmp.add(e3); sEmp.add(e4); sEmp.add(e5); for(Employee e : sEmp){ System.out.println(e); } ``` So I get all the objects data being printed on my console as : ``` Abc 77.0 1 Abc 2.0 1 Mno 5.0 2 XYZ 4.0 3 abc 3.0 4 ``` AFAIK, the set does not allow duplicates and this duplicay will be check on `equals` (correct me if I am wrong). Also, `HashSet` uses the `hashCode`, so in above case, it should not add the object `e5`. But it successfully adds that element to the set. This confused me. (Please ignore if I have missed standards and all that stuff, I am trying to understand the concept/implementation). EDITED : This may sound a dumb question, but I am preparing for certification ans was trying to see how stuff works.