Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Do not violate any of the first three conditions when implementing the compareTo() method. Implementing the fourth condition is strongly recommended but is not necessary.

Noncompliant Code Example

This noncompliant code example violates the third condition (transitivity) in the contract. This requirement states that the objects that compareTo() considers equal (by returning 0) must be ordered the same with respect to other objects. For example, a card may require to be compared against any other card to check whether both belong to the same suit or have the same rank. If neither of these conditions is true, compareTo() is expected to order the cards based on rank alone. This situation may arise in a game like Uno or Crazy Eights, where one can only place a card on the pile that shares a suit or rank with the top most card on the pile.

...

Here, the comparison between (a,c) yields that c is larger. However, the comparison (b,c) yields b as larger. This means b must be larger than a. However, comparing (a,b) results in the value 0 implying that both a and b compare equal.

Compliant Solution

This compliant solution ensures that the compareTo() contract is satisfied, and the corresponding equals() method is consistent with compareTo().

...

As required by the ordering, c is larger than both a and b and the comparison (a,b) produces an equal result. This maintains the compareTo() method's contract.

Risk Assessment

Violating the general contract when implementing the compareTo() method can lead to unexpected results, possibly leading to invalid comparisons and information disclosure.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET34- J

medium

unlikely

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C++ Secure Coding Standard as ARR40-CPP. Use a Valid Ordering Rule.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] method [compareTo()|http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html#compareTo(java.lang.Object)]
\[[JLS 05|AA. Java References#JLS 05]\]

...