Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added import for Comparator and also made the CS more comprable to the NCE

...

This noncompliant code example defines a Comparator with a compare() method [Bloch 2009]. The compare() method accepts two boxed primitives as arguments. The == operator is used to compare the two boxed primitives. In this context, however, it compares the references to the wrapper objects rather than comparing the values held in those objects.

Code Block
bgColor#FFCCCC
import java.util.Comparator;
 
static Comparator<Integer> cmp = new Comparator<Integer>() {
  public int compare(Integer i, Integer j) {
    return i < j ? -1 : (i == j ? 0 : 1);
  } 
};

...

This compliant solution uses the comparison operators, <, >, <=, or >=, because these cause automatic unboxing of the primitive values. The == and != operators should not be used to compare boxed primitives.

Code Block
bgColor#ccccff
import java.util.Comparator;
 
static Comparator<Integer> cmp = new Comparator<Integer>() { 
  public int compare(Integer i, Integer j) {
    return i < j ? -1 : (i > j ? 1 : 0) ;
  }
};

Noncompliant Code Example

...