Changing hashCode of object stored in hash-based collection

前端 未结 5 1301
孤独总比滥情好
孤独总比滥情好 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:33

    If you add an object to a hash-based collection, then mutate its state so as to change its hashcode (and by implication probably the behaviour in .equals() calls), you may see effects including but not limited to:

    • Stuff you put in the collection seeming to not be there any more
    • Getting something out which is different to what you asked for

    This is surely not what you want. So, I recommend making the hashcode only out of immutable fields. This is usually done by making the fields final and setting their values in the constructor.

提交回复
热议问题