Objects that serve as keys in ordered sets and maps should be immutable. When some fields must be mutable, the {{ Wiki Markup 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|AA. References#API 06]\]:
...
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: the {{equals
}} and {{hashCode
}} methods are no longer well defined on such a map.
Noncompliant Code Example
...
Many programmers are surprised by an instance of hash code mutability that arises because of serialization. The contract for the hashCode()
method lacks any requirement that hash codes remain consistent across different executions of an application. Similarly, when an object is serialized and subsequently deserialized, its hashcode after deserialization may be inconsistent with its original hashcode.
This noncompliant code example uses the {{ Wiki Markup 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|AA. References#API 06]\] class {{Hashtable
}} documentation:
To successfully store and retrieve objects from a hash table, the objects used as keys must implement the
hashCode
method and theequals
method.
...
Some available static analysis tools can detect instances where the compareTo()
method is reading from a nonconstant field.
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="131818a1-f31b-489f-926a-de5aca11abd1"><ac:plain-text-body><! [CDATA[ [[API 2006AA. References#API 06] ] | |
...