Wiki Markup |
---|
Keys ofObjects that serve as keys in ordered sets and maps should typically be immutable. When Ifsome thisfields ismust notbe possiblemutable, ensure that the {{equals()}} and {{compareTo()}} methods doconsider not take into account the mutable only immutable state while comparing objects. FailureViolations toof do this, forrule example, can produce inconsistent orderings in collections. The documentation of {{java.util.Interface Set<E>}} and {{java.util.Interface Map<K,V>}} warn against this \[[API 2006|AA. Bibliography#API 06]\]: |
exercised if 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
Wiki Markup Note: great care must beequals
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.
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: the {{equals}} and {{hashCode}} methods are no longer well defined on such a map.
Noncompliant Code Example
...
Use of the Employee
object as a key for the map is insecure because the properties of the object may change when after an ordering has already been established. For example, a client may modify the name
field when the last name of an employee changes. Consequently, clients may observe non-deterministic behavior.
...