You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

The values of boxed primitives cannot be compared using the == and != operators by default. This is because these are interpreted as reference comparison operators.

Noncompliant Code Example

This noncompliant example (adopted from [[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. This however, compares their references and not the actual values.

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

Compliant Solution

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

public int compare(Integer i, Integer j) {
  return i < j ? -1 : (i > j ? 1 : 0) ;
}

Risk Assessment

Using the equal and not equal operators to compare boxed primitives can lead to erroneous comparisons.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP32- J

low

likely

medium

P6

L2

Automated Detection

TODO

Related Vulnerabilities

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

References

[[Bloch 09]] 4. "Searching for the One"
[[Pugh 09]] Using == to compare objects rather than .equals


EXP31-J. Avoid side effects in assertions      03. Expressions (EXP)      04. Scope (SCP)

  • No labels