CWE-595: Comparison of Object References Instead of Object Contents
Comparison of Object References Instead of Object Contents
Weakness ID: 595 (Weakness Base)
Status: Incomplete
Description
Description Summary
The program compares object references instead of the contents
of the objects themselves, preventing it from detecting equivalent
objects.
Time of Introduction
Implementation
Demonstrative Examples
Example 1
In the following example, two Truck objects are compared using the
== operator (incorrect) as opposed to calling the equals() method
(correct).
(Bad Code)
Java
public boolean compareTrucks(Truck a, Truck b) {
return a == b;
}
Potential Mitigations
Phase
Description
Use the equals() method to compare objects instead of the == operator.
If using ==, it is important for performance reasons that your objects
are created by a static factory, not by a constructor.
Other Notes
This problem can cause unexpected application behavior. Comparing objects
using == usually produces deceptive results, since the == operator compares
object references rather than values. To use == on a string, the programmer
has to make sure that these objects are unique in the program, that is, that
they don't have the equals method defined or have a static factory that
produces unique objects.