我正在将对象添加到hashSet,iam覆盖hashcode()和equals()。我有意在这些对象相等但仍添加到hashSet?
哈希码传递不同的实例变量是差异但对象相等仍然是既在HashSet的插入
代码:
HashSet hs = new HashSet();
employee e1 = new employee();
employee e2 = new employee();
e1.setname("amol1"); e1.setcity("bombay");
e2.setname("amol1"); e2.setcity("delhi");
System.out.println("e1 --> "+e1.hashCode()+ " and e2 --> " +e2.hashCode() + " " + e1.equals(e2));
hs.add(e1); hs.add(e2)
重写的方法:
@Override
public int hashCode()
{
return city.hashCode();
}
@Override
public boolean equals(Object o)
{
employee e = (employee)o;
return getname().equalsIgnoreCase(e.getname());
}
它们可能具有相同的'name'(因此是“相等”),但它们有不同的'hashCode's!所以他们去不同的桶,平等不检查。 –
不等于在hashSet中添加对象的优先级...我在headfirst中读取 – Amol
@BenjaminLowry他想知道为什么即使它们具有相同的值,对象也会被添加。 –