[英]Java HashSet contains duplicates if contained element is modified
[英]Java hashset contains duplicates
我有一個Car對象的哈希集,例如Set<Car> cars = new HashSet<Car>
。
汽車課簡要介紹如下
public abstract class Car {
protected Piece current;
protected Piece;
....
....
....
@Override
public booleanll) return false;
if ((obj.getClass() == this.getClass())) {
Car o = (Carrent.equals(o.current) && other.equals(o.other)) || (current.equals) && other.et)));
}
return false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((current == null) ? 0 : current.hashCode());
result = prime =pokmob result;
}
正如您在上面看到的,Car是一個抽象類,因此我還有另外兩個類BigCar
和SmallCar
擴展了Car抽象類。 我的集合包含BigCar和SmallCar對象。 還要注意,這些子類不會覆蓋equals和hashcode方法。
在您的hashCode
方法中,這兩個字段不是對稱處理的-因此,交換了current
車位和other
位置的兩輛汽車將不會具有相同的哈希碼。
例如,您可以改用此方法(也請注意使用Objects::hash
以避免進行空檢查):
@Override public int hashCode() {
return Objects.hash(current) * Objects.hash(other);
}
好吧,在您的hashCode
current
和other
不可互換。
讓分別表示current
的值作為x
和other
的值作為y
一些實例。
hashCode
值為31*(31+x)+y
。
現在,對於另一個實例,如果other
是x
並且current
是y
(這意味着第二個實例應該等於第一個實例),則hashCode
現在為31*(31+y)+x
,不等於31*(31+x)+y
適用於x
和y
大多數值。
因此,您違反了hashCode
的約定,因為如果a.equals(b) == true
,則a.hashCode()
必須等於b.hashCode()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.