Java: Modify id that changes hashcode

混江龙づ霸主 提交于 2019-12-06 03:19:42

问题


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.


回答1:


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:

  1. Remove the object, change it and add it again - works wonderful, easiest way if a HashSet is mandatory

  2. 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.



来源:https://stackoverflow.com/questions/11530061/java-modify-id-that-changes-hashcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!