Versions Compared

Key

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

...

Wiki Markup
This noncompliant code example (adopted from \[[Bloch 09|AA. Java References#Bloch 09]\]), defines a {{Comparator}} with a {{compare()}} method. The {{compare()}} method accepts two boxed primitives as arguments. Note that primitive integers are also accepted by this declaration as they are appropriately autoboxed. The main issue is that the {{==}} operator is being used to compare the two boxed primitives. However, this compares their references and not the actual values. 

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

Note that primitive integers are also accepted by this declaration as they are appropriately autoboxed. The main issue is that the == operator is being used to compare the two boxed primitives. However, this compares their references and not the actual values.

Compliant Solution

To be compliant, use any of the four comparison operators <, >, <= and >=. The == and != operators should not be used to compare boxed primitives.

...