Changing hashCode of object stored in hash-based collection

前端 未结 5 1304
孤独总比滥情好
孤独总比滥情好 2021-01-15 12:02

I have a hash-based collection of objects, such as HashSet or HashMap. What issues can I run into when the implementation of hashCode()

5条回答
  •  佛祖请我去吃肉
    2021-01-15 12:40

    If the hash code of the same object changes over time, the results are basically unpredictable. Hash collections use the hash code to assign objects to buckets -- if your hash code suddenly changes, the collection obviously doesn't know, so it can fail to find an existing object because it hashes to a different bucket now.

    Returning an object's ID by itself isn't bad, but if many of them have id=0 as you mentioned, it will reduce the performance of the hash table: all objects with the same hash code go into the same bucket, so your hash table is now no better than a linear list.

    Update: Theoretically, your hash code can change as long as nobody else is aware of it -- this implies exactly what @bestsss mentioned in his comment, which is to remove your object from any collections that may be holding it and insert it again once the hash code has changed. In practice, a better alternative is to generate your hash code from the actual content fields of your object rather than relying on the database ID.

提交回复
热议问题