...
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i > j ? 1 : 0) ;
}
|
...
This noncompliant code example uses the ==
operator in an attempt to compare the values of pairs of Integer
objects. However, the ==
operator compares object references rather than object values.
Code Block | ||
---|---|---|
| ||
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1 == i2);
System.out.println(i1 != i2);
System.out.println(i3 == i4);
System.out.println(i3 != i4);
}
}
|
The Integer
class is only guaranteed to cache integer values from -128
to 127
, which can result in equivalent values outside this range comparing as unequal when tested using the equality operators. For example, a Java Virtual Machine (JVM) that did not cache any other values when running this program would output
Code Block |
---|
true
false
false
true
|
Compliant Solution
This compliant solution uses the equals()
method instead of the ==
operator to compare the values of the objects. The program now prints true
, false
, true
, false
on all platforms, as expected.
Code Block | ||
---|---|---|
| ||
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1.equals(i2));
System.out.println(!i1.equals(i2));
System.out.println(i3.equals(i4));
System.out.println(!i3.equals(i4));
}
}
|
...
This noncompliant code example attempts to count the number of indices in arrays list1
and list2
that have equivalent values. Recall that class Integer
is required to memoize only those integer values in the range -128 to 127; it might return a nonunique object for any value outside that range. Consequently, when comparing autoboxed integer values outside that range, the ==
operator might return false
and the example could deceptively output 0.
Code Block | ||
---|---|---|
| ||
public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers, where each element
// is greater than 127
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first list
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values.
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i) == list2.get(i)) { // uses '=='
counter++;
}
}
// Print the counter: 0 in this example
System.out.println(counter);
}
}
|
...
This compliant solution uses the equals()
method to perform value comparisons of wrapped objects. It produces the correct output 10.
Code Block | ||
---|---|---|
| ||
public class Wrapper {
public static void main(String[] args) {
// Create an array list of integers
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list1.add(i + 1000);
}
// Create another array list of integers, where each element
// has the same value as the first one
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list2.add(i + 1000);
}
// Count matching values
int counter = 0;
for (int i = 0; i < 10; i++) {
if (list1.get(i).equals(list2.get(i))) { // uses 'equals()'
counter++;
}
}
// Print the counter: 10 in this example
System.out.println(counter);
}
}
|
...
In this noncompliant code example, constructors for class Boolean
return distinct newly-instantiated objects. Using the reference equality operators in place of value comparisons will yield unexpected results.
Code Block | ||
---|---|---|
| ||
public void exampleEqualOperator(){
Boolean b1 = new Boolean("true");
Boolean b2 = new Boolean("true");
if (b1 == b2) { // never equal
System.out.println("Never printed");
}
}
|
...
In this compliant solution, the values of autoboxed Boolean
variables may be compared using the reference equality operators because the Java language guarantees that the Boolean
type is fully memoized. Consequently, these objects are guaranteed to be singletons.
Code Block | ||
---|---|---|
| ||
public void exampleEqualOperator(){
Boolean b1 = true; // Or Boolean.True
Boolean b2 = true; // Or Boolean.True
if (b1 == b2) { // always equal
System.out.println("Always print");
}
}
|
...
Detection of all uses of the reference equality operators on boxed primitive objects is straightforward. Determining the correctness of such uses is infeasible in the general case.
Tool | Version | Checker | Description |
---|---|---|---|
Coverity | 7.5 | BAD_EQ FB.EQ_ABSTRACT_SELF FB.EQ_ALWAYS_FALSE FB.EQ_ALWAYS_TRUE FB.EQ_CHECK_FOR_OPERAND_NOT_ COMPATIBLE_WITH_THIS FB.EQ_COMPARETO_USE_OBJECT_ EQUALS FB.EQ_COMPARING_CLASS_NAMES FB.EQ_DOESNT_OVERRIDE_EQUALS FB.EQ_DONT_DEFINE_EQUALS_ FOR_ENUM FB.EQ_GETCLASS_AND_CLASS_ CONSTANT FB.EQ_OTHER_NO_OBJECT FB.EQ_OTHER_USE_OBJECT FB.EQ_OVERRIDING_EQUALS_ NOT_SYMMETRIC FB.EQ_SELF_NO_OBJECT FB.EQ_SELF_USE_OBJECT FB.EQ_UNUSUAL | Implemented |
Related Guidelines
CWE-595. Comparison of object references instead of object contents | |
| CWE-597. Use of wrong operator in string comparison |
...
4, Searching for the One | |
[JLS 2005] | |
Using == to Compare Objects Rather than |