我讀過這樣一個問題:Changing the elements in a set changes the 'equals' semantics更改值HashSet的
不過,我不知道怎麼解決,我不能在HashSet中改變一個項目,後來刪除的問題。
我有一些示例源代碼:
public static void main(String[] args) {
TestClass testElement = new TestClass("1");
Set<TestClass> set = new HashSet<>();
set.add(testElement);
printIt(testElement, set, "First Set");
testElement.setS1("asdf");
printIt(testElement, set, "Set after changing value");
set.remove(testElement);
printIt(testElement, set, "Set after trying to remove value");
testElement.setS1("1");
printIt(testElement, set, "Set after changing value back");
set.remove(testElement);
printIt(testElement, set, "Set removing value");
}
private static void printIt(TestClass hullo, Set<TestClass> set, String message) {
System.out.println(message + " (hashCode is " + hullo.hashCode() + "):");
for (TestClass testClass : set) {
System.out.println(" " + testClass.toString());
System.out.println(" HashCode: " + testClass.hashCode());
System.out.println(" Element is equal: " + hullo.equals(testClass));
}
}
哪裏TestClass的僅僅是持有變量(加上吸氣&二傳手),並具有hashCode()和equals()方法實現的POJO。
有一個請求顯示equals()和hashcode()方法。這些是通過蝕自動生成:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((s1 == null) ? 0 : s1.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestClass other = (TestClass) obj;
if (s1 == null) {
if (other.s1 != null)
return false;
} else if (!s1.equals(other.s1))
return false;
return true;
}
結果如下:
First Set (hashCode is 80):
TestClass [s1=1]
HashCode: 80
Element is equal: true
Set after changing value (hashCode is 3003475):
TestClass [s1=asdf]
HashCode: 3003475
Element is equal: true
Set after trying to remove value (hashCode is 3003475):
TestClass [s1=asdf]
HashCode: 3003475
Element is equal: true
Set after changing value back (hashCode is 80):
TestClass [s1=1]
HashCode: 80
Element is equal: true
Set removing value (hashCode is 80):
當哈希碼已經改變,我無法從HashSet的刪除值。正如在linked question,我明白爲什麼它是這樣的,但我不知道如何刪除更改的值。有沒有可能這樣做?
你可以發佈hashcode和equals方法嗎? – mabbas
@mabbas編輯。 – looper