An object is characterized by its identity (location in memory) and state (actual data). While the '==' operator compares only the identities of two objects (to check if both the references are actually the same object), the equals method defined in java.lang.Object can compare the state as well, when customized by overriding it. The equals method only applies to Objects, not primitives.
The general usage contract for equals() has been put forth verbatim from the Java specification:
x.equals(x) must return true.x.equals(y) must return true if and only if y.equals(x) returns true.x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.x.equals(null) must return false.Do not violate any of these five conditions while overriding the equals method.
This noncompliant code example violates the second condition in the contract (symmetry). This requirement means that if one object is equal to another then the other must also be equal to this one. Consider a CaseInsensitiveString class that defines a String and overrides the equals method. The CaseInsensitiveString knows about ordinary strings but the String class has no idea about case-insensitive strings. As a result, s.equalsIgnoreCase(((CaseInsensitiveString)o).s) returns true but s.equalsIgnoreCase((String)o) always returns false.
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null)
throw new NullPointerException();
this.s = s;
}
//This method violates asymmetry
public boolean equals(Object o) {
if (o instanceof CaseInsensitiveString)
return s.equalsIgnoreCase(((CaseInsensitiveString)o).s);
if (o instanceof String)
return s.equalsIgnoreCase((String)o);
return false;
}
public static void main(String[] args) {
CaseInsensitiveString cis = new CaseInsensitiveString("Java");
String s = "java";
System.out.println(cis.equals(s)); //returns true
System.out.println(s.equals(cis)); //returns false
}
}
|
Do not try to inter-operate with String from the equals method. The new equals method is highlighted in this compliant solution.
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null)
throw new NullPointerException();
this.s = s;
}
public boolean equals(Object o) {
return o instanceof CaseInsensitiveString &&
((CaseInsensitiveString)o).s.equalsIgnoreCase(s);
}
public static void main(String[] args) {
CaseInsensitiveString cis = new CaseInsensitiveString("Java");
String s = "java";
System.out.println(cis.equals(s)); //returns false now
System.out.println(s.equals(cis)); //returns false now
}
}
|
This noncompliant example violates transitivity though it follows the symmetry condition. This is because the first two statements print true while the third prints false. A practical implementation issue is intermingling of java.sql.Timestamp and java.util.Date classes. There is a disclaimer about the erratic behavior in the documentation for the Timestamp class.
public class Card {
private final int number;
public Card(int number) {
this.number = number;
}
public boolean equals(Object o) {
if (!(o instanceof Card))
return false;
Card c = (Card)o;
return c.number == number;
}
}
class XCard extends Card {
private String type;
public XCard(int number, String type) {
super(number);
this.type = type;
}
public boolean equals(Object o) {
if (!(o instanceof Card))
return false;
//normal Card, do not compare type
if (!(o instanceof XCard))
return o.equals(this);
//It is an XCard, compare type as well
XCard xc = (XCard)o;
return super.equals(o) && xc.type == type;
}
public static void main(String[] args) {
XCard p1 = new XCard(1, "type1");
Card p2 = new Card(1);
XCard p3 = new XCard(1, "type2");
System.out.println(p1.equals(p2)); //returns true
System.out.println(p2.equals(p3)); //returns true
System.out.println(p1.equals(p3)); //returns false, violating transitivity
}
}
|
"There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract." This implies that composition must be preferred over inheritance in this case. This is done by giving the {{XCard}} class a private {{card}} field and providing a a public {{viewCard}} method. \[[Bloch 08|AA. Java References#Bloch 08]\] |
public class Card {
private final int number;
public Card(int number) {
this.number = number;
}
public boolean equals(Object o) {
if (!(o instanceof Card))
return false;
Card c = (Card)o;
return c.number == number;
}
}
class XCard extends Card {
private String type;
private Card card;
public XCard(int number, String type) {
super(number);
this.type = type;
}
public Card viewCard() {
return card;
}
public boolean equals(Object o) {
if (!(o instanceof XCard))
return false;
XCard cp = (XCard)o;
return cp.card.equals(card) && cp.type.equals(type);
}
public static void main(String[] args) {
XCard p1 = new XCard(1, "type1");
Card p2 = new Card(1);
XCard p3 = new XCard(1, "type2");
System.out.println(p1.equals(p2)); //returns false
System.out.println(p2.equals(p3)); //returns false
System.out.println(p1.equals(p3)); //returns false
}
}
|
TODO: Add condition for hashcode
Violating the general contract when overriding the equals() method can lead to unexpected results.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
MET30-J |
low |
unlikely |
medium |
P2 |
L3 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[API 06|AA. Java References#API 06]\] [method equals()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)] \[[Bloch 08|AA. Java References#Bloch 08]\] Item 8: Obey the general contract when overriding equals |
MET03-J. Return zero-length arrays instead of null values 09. Methods (MET) MET31-J. Ensure that hashCode() is overridden when equals() is overridden