Objects that serve as keys in ordered sets and maps should be immutable. When some fields must be mutable, the equals()
, hashCode()
, and compareTo()
methods must consider only immutable state when comparing objects. Violations of this rule can produce inconsistent orderings in collections. The documentation of java.util.Interface Set<E>
and java.util.Interface Map<K,V>
warns against this. For example, the documentation for the Interface Map
states [API 2014]:
Note: great care must be exercised [when] mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects
equals
comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: theequals
andhashCode
methods are no longer well defined on such a map.
...
Some available static analysis tools can detect instances where the compareTo()
method is reading from a nonconstant field.
Bibliography
...