IF we add two different objects(mutable) in HashSet and after that change the value of the objects by calling setter(making them same), the size remains 2 of the hashSet
I am not able to understand the reason for the same :
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Amit");
Employee e1 = new Employee();
e1.setName("Jitender");
Set<Person> hashSet = new HashSet<Person>();
hashSet.add(e);
hashSet.add(e1);
// size of set is >>2
System.out.println("size of set is >>" + hashSet.size());
e1.setName("Amit");
// updated size of set is >>2
System.out.println("updated size of set is >>" + hashSet.size());
}
Employee class is :
public class Employee extends Person {
public Employee() {
}
public Employee(String name) {
this.name = name;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
Employee e = (Employee) obj;
return this.name.equals(e.name);
}
}
HashSetis not intended to react to changes in the objects it contains. In fact, the documentation warns against adding mutable objects to a set and modifying them.From the
Setinterface documentation:( Another point is that
HashSetuses the members’equals()andhashCode()methods, which means that if you did not implement those methods for yourEmployee, twoEmployees will not be equal unless they are two references to the sameEmployeeobject. ) In your edit you show that you implemented that.On a practical “what happens if I do this anyway?” note, if you look at the source code of
HashMap(b/c aHashSetis implemented as aHashMapthat maps the entries you insert to a dummy object) you can see that the size is only updated when you add and remove variables, and that even when the table is rehashed to increase the capacity, there are no equality checks, so your duplicate objects will stay in that set that you just broke by doing what you shouldn’t have been doing in the first place.