Versions Compared

Key

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

...

Never violate any of the first three conditions when implementing the compareTo() method. Implementations should conform to the fourth condition whenever possible.

Noncompliant Code Example (

...

Rock-

...

Paper-

...

Scissors)

This program implements the classic game of rock-paper-scissors, using the compareTo() operator to determine the winner of a game.

...

However, this game violates the notion of transitivity , because Rock beats Scissors, Scissors beats Paper, but Rock does not beat Paper.

Compliant Solution (

...

Rock-

...

Paper-

...

Scissors)

This compliant solution implements the same game , but does not use the Comparable interface.

...

The Coverity Prevent Version 5.0 MUTABLE_COMPARISON checker can detect the instances where compareTo method is reading from a non-constant field. If the non-constant field is modified, the value of compareTo might change, which may break program invariants.

...