Consider the employee class -
public class Employer implements Serializable{
private Long id;
private String name;
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj instanceof Employer) {
Employer employer = (Employer) obj;
if (this.id == employer.id) {
return true;
}
}
return false;
}
//Idea from effective Java : Item 9
@Override
public int hashCode() {
int result = 17;
result = 31 * result + id.hashCode();
//result = 31 * result + name.hashCode();
return result;
}
}
With 2 employee objects created -
Employer employer1 = new Employer();
employer1.setId(10L);
Employer employer2 = new Employer();
employer2.setId(11L);
After adding them to the hashset, the size will be 2. HashSet internally uses a hashmap to maintain the uniqueness-
private transient HashMap<E,Object> map;
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
Now, if I set the id for the second employee to be same as that of the first, i.e-
employer2.setId(10L);
the size still remains 2. Why is it not 1? Does the in-variants get destroyed?