mutable fields for objects in a Java Set

后端 未结 4 1778
悲&欢浪女
悲&欢浪女 2020-12-16 18:18

Am I correct in assuming that if you have an object that is contained inside a Java Set<> (or as a key in a Map<> for that matter), any fields that are used to determi

4条回答
  •  一整个雨季
    2020-12-16 18:28

    The javadoc for Set says

    Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

    This simply means you can use mutable objects in a set, and even change them. You just should make sure the change doesn't impact the way the Set finds the items. For HashSet, that would require not changing the fields used for calculating hashCode().

提交回复
热议问题