CWE-595: Comparison of Object References Instead of Object Contents
Description
The product compares object references instead of the contents of the objects themselves, preventing it from detecting equivalent objects.
Submission Date :
Dec. 15, 2006, midnight
Modification Date :
2023-06-29 00:00:00+00:00
Organization :
MITRE
Extended Description
For example, in Java, comparing objects using == usually produces deceptive results, since the == operator compares object references rather than values; often, this means that using == for strings is actually comparing the strings' references, not their values.
Example - 1
In the example below, two Java String objects are declared and initialized with the same string values. An if statement is used to determine if the strings are equivalent. However, the if statement will not be executed as the strings are compared using the "==" operator. For Java objects, such as String objects, the "==" operator compares object references, not object values. While the two String objects above contain the same string values, they refer to different object references, so the System.out.println statement will not be executed. To compare object values, the previous code could be modified to use the equals method:
System.out.println("str1 == str2");String str1 = new String("Hello");String str2 = new String("Hello");if (str1 == str2) {}
System.out.println("str1 equals str2");if (str1.equals(str2)) {}
Example - 2
In the following Java example, two BankAccount objects are compared in the isSameAccount method using the == operator.
return accountA == accountB;public boolean isSameAccount(BankAccount accountA, BankAccount accountB) {}
Using the == operator to compare objects may produce incorrect or deceptive results by comparing object references rather than values. The equals() method should be used to ensure correct results or objects should contain a member variable that uniquely identifies the object.
The following example shows the use of the equals() method to compare the BankAccount objects and the next example uses a class get method to retrieve the bank account number that uniquely identifies the BankAccount object to compare the objects.
return accountA.equals(accountB);public boolean isSameAccount(BankAccount accountA, BankAccount accountB) {}
Related Weaknesses
This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.
Visit http://cwe.mitre.org/ for more details.