在我的代碼我有一組PlacesInfo對象即,如何重寫hashcode和equals方法以避免在java中的HashSet中添加重複的字符串?
Set<PlacesInfo> placeId;
在這集我加入placeId(字符串)。我需要避免將重複項添加到我的HashSet。下面是我的覆蓋方法。但是,它仍然是添加重複元素到我的設置。那麼,如何避免這一點?
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.placeId);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return true;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final PlacesInfo other = (PlacesInfo) obj;
if (!Objects.equals(this.placeId, other.placeId)) {
return false;
}
return true;
}
我假設給定的'hashCode'和'equals'方法是'PlacesInfo'類的一部分。我無法用你的方法使用'HashSet'重現這一點。一些更多的代碼可能有助於追蹤錯誤。 [來源](http://ideone.com/HURDbi) – Obicere 2015-03-02 04:57:18
對於初學者來說,你的'equals'方法說你的所有對象都等於null。 – chrylis 2015-03-02 06:04:58
'placeId'是什麼類型? – Mureinik 2015-03-02 07:59:23