如果我们在 HashSet 中添加两个不同的对象(可变),然后通过调用 setter 更改对象的值(使它们相同),则 hashSet 的大小保持为 2
我无法理解相同的原因:
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());
}
员工类是:
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);
}
}