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

Compare with Current View Page History

Version 1 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

P4

L3

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"


EXP31-J. Avoid side effects in assertions      02. Expressions (EXP)      02. Expressions (EXP)

  • No labels