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 2006]:
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.
...
This noncompliant code example uses the MyKey
class as the key index for the Hashtable
. The MyKey
class overrides Object.equals()
, but uses the default Object.hashCode()
. According to the Java API [API 2006] class Hashtable
documentation:
...
Some available static analysis tools can detect instances where the compareTo()
method is reading from a nonconstant field.
Bibliography
[API 2006] | |
...