Java:修改改变哈希码的ID [英] Java: Modify id that changes hashcode
问题描述
我使用HashSet,我需要修改一个对象的ID,但它会更改散列码并打破HashSet和hashCode()方法的规则。
什么是最佳解决方案:从Set中删除对象并添加具有新ID的对象,或者将哈希代码(例如在构造函数中生成)保存在每个对象中设置,还是有其他方法来解决这个问题?
感谢您的帮助。
更新:
我犯了错误:保持散列码在对象中可怕的是,因为在这种情况下,相同的对象可以有不同的哈希码。
对象说:维护hashCode()方法的一般合约,对象必须具有相同的哈希代码
正如您注意到的,如果您更改了保存在HashSet中的对象的状态,则不能再通过删除方法或通过HashMap的contains方法找到。
您提供的选项是:
-
移除该对象,将其修改并重新添加 -
的功能非常强大,如果HashSet是强制性的,那么最简单的方法就是
保持哈希码某处的值 - 意思是说,对于不相等的对象,你有相同的哈希码。或者,如果你服从文档,你可能会遇到两个对象,它们是相等的并且具有相同的散列码,但是它们的成员变量不同!这可能会导致不可预知的错误。
Remove the object, change it and add it again - works wonderful, easiest way if a HashSet is mandatory
Keep the value of the hash code 'somewhere' - Means, you have the same hash code for objects which are not equal. Or if you obey the documentation you can encounter two objects which are equals and have the same hash code, but their member variables differ! This can lead to unpredictable errors.
I use HashSet and I need to modify the ID of an object, but it changes hashcode and breaks HashSet and rules of hashCode() method.
What is best solution: to delete object from Set and add object with new ID, or to keep the hash code (generated in constructor, for example) in every object in Set, or is there other way to solve this problem?
Thanks for help.
UPDATE: I made mistake: keeping hash code in object is terrible, because in that case equal objects can have different hash codes.
A HashSet as a container accesses its items (contains, remove) via the hash code of the items you put into it. The hash code is often built by the state of its instance members. So the hash code changes with the manipulation of the state of the object.
The documentation of Object says: "maintain the general contract for the hashCode() method, which states that equal objects must have equal hash codes"
As you noticed, if you change the state of an object you keep in a HashSet, the object can not longer be accessed by the remove method or found by the contains method of the HashMap.
The options you are offering are:
这篇关于Java:修改改变哈希码的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!