Tôi đã đọc câu hỏi này: Changing the elements in a set changes the 'equals' semanticsgiá trị thay đổi trong HashSet
Tuy nhiên, tôi không biết làm thế nào để giải quyết vấn đề mà tôi không thể thay đổi một mục trong HashSet và loại bỏ nó sau này.
Tôi có một số ví dụ sourcecode:
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));
}
}
đâu TestClass chỉ là một POJO chứa một biến (cộng getter & setter) và có hashcode() và equals() thực hiện.
Đã có yêu cầu hiển thị phương thức equals() và hashcode() -. Đây là những autogenerated bởi eclipse:
@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;
}
Kết quả như sau:
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):
Khi hashcode đã thay đổi, tôi không thể loại bỏ các giá trị từ HashSet. Như trong số linked question, tôi hiểu được lý do tại sao nó giống như vậy, nhưng tôi không biết cách xóa giá trị đã thay đổi. Có khả năng làm như vậy không?
Bạn có thể đăng phương thức hashcode và equals không? – mabbas
@mabbas đã chỉnh sửa. – looper