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.
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.
This is standard example of why we should be using @Override annotation wherever possible.
If you would use this annotation with your equals method, you would be informed by compiler that you are not overriding equals method, because there is no equals(Employe) method in superclass, but equals(Object). So you are overloading this method (you are creating additional method with different arguments).
Because of this HashSet is not using code of your equals method, but code from equals(Object) method inherited from Object class which just checks references equality:
public boolean equals(Object obj) {
return (this == obj);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With