Java: Modify id that changes hashcode

天大地大妈咪最大 提交于 2019-12-04 07:10:05

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.

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