Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

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: the equals and hashCode methods are no longer well defined on such a map.

...

Failure to ensure that the keys used in a comparison operation are immutable can lead to nondeterministic behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET11-J

Low

Probable

High

P2

L3

Automated Detection

Some available static analysis tools can detect instances where the compareTo() method is reading from a nonconstant field.

ToolVersionCheckerDescription
Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.MET11.IKICOEnsure that keys used in comparison operations are immutable

Bibliography

...


...

Image Modified Image Modified Image Modified