75 lines
2.4 KiB
Plaintext
75 lines
2.4 KiB
Plaintext
It is equivalent to use the equality <code>==</code> operator and the <code>equals</code> method to compare two objects if the <code>equals</code> method inherited from <code>Object</code> has not been overridden. In this case both checks compare the object references.
|
|
|
|
But as soon as <code>equals</code> is overridden, two objects not having the same reference but having the same value can be equal. This rule spots suspicious uses of <code>==</code> and <code>!=</code> operators on objects whose <code>equals</code> methods are overridden.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
String firstName = getFirstName(); // String overrides equals
|
|
String lastName = getLastName();
|
|
|
|
if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
String firstName = getFirstName();
|
|
String lastName = getLastName();
|
|
|
|
if (firstName != null && firstName.equals(lastName)) { ... };
|
|
----
|
|
|
|
== Exceptions
|
|
|
|
Comparing two instances of the <code>Class</code> object will not raise an issue:
|
|
|
|
----
|
|
Class c;
|
|
if(c == Integer.class) { // No issue raised
|
|
}
|
|
----
|
|
|
|
Comparing <code>Enum</code> will not raise an issue:
|
|
|
|
----
|
|
public enum Fruit {
|
|
APPLE, BANANA, GRAPE
|
|
}
|
|
public boolean isFruitGrape(Fruit candidateFruit) {
|
|
return candidateFruit == Fruit.GRAPE; // it's recommended to activate S4551 to enforce comparison of Enums using ==
|
|
}
|
|
----
|
|
|
|
Comparing with <code>final</code> reference will not raise an issue:
|
|
|
|
----
|
|
private static final Type DEFAULT = new Type();
|
|
|
|
void foo(Type other) {
|
|
if (other == DEFAULT) { // Compliant
|
|
//...
|
|
}
|
|
}
|
|
----
|
|
|
|
Comparing with <code>this</code> will not raise an issue:
|
|
|
|
----
|
|
public boolean equals(Object other) {
|
|
if (this == other) { // Compliant
|
|
return false;
|
|
}
|
|
}
|
|
----
|
|
|
|
Comparing with <code>java.lang.String</code> and boxed types <code>java.lang.Integer</code>, ... will not raise an issue.
|
|
|
|
== See
|
|
|
|
* S4973 - Strings and Boxed types should be compared using "equals()"
|
|
* http://cwe.mitre.org/data/definitions/595.html[MITRE, CWE-595] - Comparison of Object References Instead of Object Contents
|
|
* http://cwe.mitre.org/data/definitions/597.html[MITRE, CWE-597] - Use of Wrong Operator in String Comparison
|
|
* https://www.securecoding.cert.org/confluence/x/wwD1AQ[CERT, EXP03-J.] - Do not use the equality operators when comparing values of boxed primitives
|
|
* https://www.securecoding.cert.org/confluence/x/8AEqAQ[CERT, EXP50-J.] - Do not confuse abstract object equality with reference equality
|